Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(status): MUL-7365 expand category compatibility before backfill (#8407)
Jiayuan Zhang9d18186e6e8c
diff --git a/docs/issue-status-lifecycle-rollout.md b/docs/issue-status-lifecycle-rollout.mdindex 2aac9923b8..261504b7f3 100644--- a/docs/issue-status-lifecycle-rollout.md+++ b/docs/issue-status-lifecycle-rollout.md@@ -40,46 +40,90 @@ instruction to start, finish or fail an agent. The built-in platform skill andnew daemon task briefs describe this distinction. This is not a workflow engine;PR #7990 is subsequent work, not part of this release.-## Migration and release--1. Before deploying, count catalog rows by category and active/archive state;- identify custom Backlog, In Review and Blocked usages, especially issues in- active autopilot runs. Also check historical custom keys named `unstarted`,- `started`, or `closed`: exact-key filters must continue selecting those statuses,- not interpret their keys as category filters. Tell affected users that those custom statuses will- no longer park, finish or fail automation. The decision applies to historical- custom statuses too; no legacy behavior is retained.-2. Apply migration 469 (categories) and 470 (icon), then deploy the matching backend. The catalog rewrite,- constraints and SQL behavior function change in one atomic statement. It- preserves every status ID/key/name/color/order/archive marker and every issue- reference. It does not update issues, replay events, or enqueue tasks.-3. The approximately one-minute mixed-backend window is an accepted maintenance- window, not a zero-downtime guarantee. Old pods may reject catalog writes in- that window. Finish replacing them before acceptance testing.-4. Deploy the Web/Desktop/Mobile client changes and update local daemons. New- skills/prompts take effect in newly prepared task environments; already- running agents do not have their prompt rewritten. Do not replay or restart- tasks automatically. Review affected in-flight work and move it to an- appropriate fixed built-in status only when that action is intended.-5. Verify four stored categories, seven unchanged fixed keys, unchanged row and- issue-reference counts, custom status CRUD/archive, terminal filtering, independent built-in/custom status- columns, counts, pagination and drag/create targets, and lack of unintended task enqueues. Check API error rates and- automation completion/failure paths.--Release policy is fix-forward. Do not roll back application code over the new-schema or restore a second behavior model. If migration fails, its atomic-statement leaves the prior catalog intact: diagnose and apply the corrected-forward migration. If it committed, repair with a new forward migration or-patch. The paired down file deliberately refuses reversal; reapplying the up-statement after an uncertain acknowledgement is idempotent.--Before merging, these migrations were renumbered from 467/468, then 468/469,-to 469/470 to follow main's existing 468 migrations. Main's two distinct 468-filenames are preserved, with an exact-pair exception in the numbering lint;-new collisions remain forbidden. The runner keys its ledger by the full-filename stem, not just the number. A local preview that ran the earlier names-will therefore replay the new names; both up statements are idempotent, and-icon replay preserves saved shapes. Do not rewrite or delete ledger entries.+## Migration and release (MUL-7365, phase 1)++The supported upgrade entrypoint is the **matching revision's migration runner**+(`cd server && go run ./cmd/migrate up`, with the approved target DATABASE_URL).+Do not apply pending 469 directly with psql or use an older migration binary:+469 contains the historical unbounded rewrite and is intentionally unchanged.+Production deployment and database execution require a separate operator handoff.++Before execution, collect a fresh read-only snapshot on the approved target:++```sql+SELECT version FROM schema_migrations+WHERE version LIKE '469_%' OR version LIKE '477_%' OR version LIKE '478_%';+SELECT category, is_system, archived_at IS NOT NULL AS archived, count(*)+FROM issue_status GROUP BY 1, 2, 3 ORDER BY 1, 2, 3;+SELECT conname, convalidated, pg_get_constraintdef(oid)+FROM pg_constraint WHERE conrelid = 'issue_status'::regclass;+```++The September 14 snapshot of 591,052 legacy rows is historical, not proof of the+current target's state. Compare actual constraints/data as well as the ledger:+a skipped migration is recorded, so a 469 ledger row alone does not prove a backfill.++| Starting environment | Runner behavior | Phase-1 result |+| --- | --- | --- |+| 469 has not run | Record 469 as superseded without executing its SQL; continue through 478 | Old rows remain; old/new constraints and readers coexist |+| 469 already committed | Preserve its ledger and SQL; apply additive 478 | New rows remain; the same compatibility schema is installed |+| 478 failed waiting for a lock | No 478 ledger entry; retry after contention is resolved | Its transaction rolls back; committed earlier migration entries remain |+| 478 committed but acknowledgement was lost | Resume runner; replay is safe if its ledger write was lost | No row rewrites or duplicate objects |++478 replaces only constraints and functions. The entire file is one implicit+transaction under pgx's multi-statement Exec. `SET LOCAL lock_timeout = '2s'` and+`statement_timeout = '10s'` bound this step; they do not leak to following files.+Both expanded CHECKs use NOT VALID, avoiding a validation scan under the+ACCESS EXCLUSIVE lock while still checking every subsequent write. There is no+unconstrained commit window. The constraints remain unvalidated in phase 1.+A deployment is not ready if this migration fails; diagnose contention and retry+the same runner rather than deleting ledger rows or bypassing readiness.++Release sequence:++1. Phase 1 is based on main, including the GC/recovery fix merged in PR #8405+ (MUL-7364). It builds on that GC lifecycle protocol and adds the legacy+ `cancelled` spelling to its recovery prefilter. Both are required before+ permitting data conversion.+2. Apply the matching runner through 478, then finish the agreed full backend+ replacement. Mixed storage is supported; long-lived old backend instances+ and application rollback are not part of the agreed fix-forward policy.+3. Verify old/mixed/new catalog reads, custom terminal resolution, archived+ references, create/update/reorder, old and new grouped requests, claim, both+ GC endpoints and delegated-failure recovery. No backfill needs to run for+ this release to work. New catalog inserts use four values; metadata updates,+ archive and reorder normalize touched legacy rows. All issue keys, identities,+ and custom lifecycle behavior remain unchanged by storage normalization.+4. Update clients/daemons for the new feature. Old clients remain supported by+ the wire adapters below. Old daemon prompts can still describe obsolete+ custom-status automation inheritance; upgrading the daemon is required to+ replace those instructions. Do not automatically restart or replay tasks.++**Phase 2 is a separate PR/job, not implemented by phase 1.** It must batch by+an indexed stable key, commit each batch, support dry-run/progress/retry/pause,+and include system, custom and archived catalog rows. Before starting, prove+all writers use the new format and the compatible backend is fully deployed.+Set workload limits from the environment's API latency, lock wait, I/O, WAL and+replication budgets. Pausing the job must leave normal reads/writes working.+Do not treat a skipped or failed batch as completion.++**Phase 3 is separately released after verification, never triggered by the job.**+Require zero residual old values, no old writers, correct mapping and business+invariants, and no unfinished batches. Add strict CHECKs NOT VALID in a short+transaction, commit, then VALIDATE in a separate transaction/file. Only then+retire old-storage readers. Keep the audited completion evidence. Do not put+these strict migrations into the phase-1 automatic deployment path.++Release policy is fix-forward. 478's down file preserves the compatible schema;+469 already refuses reversal. Do not roll back to code that only understands one+storage vocabulary. If any later stage fails, keep compatibility active, repair+forward and resume that stage. Do not remove client wire adapters with storage+cleanup: no minimum supported client version or retirement date has been agreed.++Migration versions 469/470 were previously renumbered during development.+Main's two historical 468 filenames retain their existing lint exception; 478+adds no collision. The runner ledger uses the full filename stem. Do not rewrite+or delete existing entries, including earlier preview-version entries.## Installed-client compatibility@@ -92,11 +136,19 @@ four categories. This is one API-boundary adapter, not a second stored modelor behavior mapping. Old category inputs are accepted on catalog creation,reordering and category filters, and normalized to the new lifecycle.-This prevents enum changes from breaking ordinary reads and writes after the-backend upgrade. It does not promise identical old UI grouping or old agent-instructions: old filters can broaden when categories combine, old saved-grouping views can require refresh/upgrade, and old daemons cannot render the-new lifecycle brief reliably. Update clients/daemons for the new feature.+The retained `group.kind: status_category` and compound+`secondary: status_category` protocols default to seven-value **wire buckets**.+Built-ins keep their own bucket; custom statuses use the same bucket as their+per-row wire category. Headers, counts, secondary_values and row pagination share+that mapping, including archived statuses and mixed storage. A category grouping+request can explicitly set `category_format: lifecycle` to use four buckets;+other values or use with a non-category group are rejected. Both group and row+cursors bind the category format; stale or cross-format cursors return the+existing 409 cursor_query_mismatch response and must restart from the first page.+These changes restore the old consumer's whitelist contract without modifying+installed clients. The general list API's legacy category-filter aliases still+normalize to lifecycle (and can broaden as categories combine), as established+in MUL-7240. Exact status filters keep their existing meanings.Board/List/Swimlane status grouping uses concrete keys, with independent customcolumns, counts and cursors. Hidden/collapsed preferences preserve exact keys;old category-named storage is read on load without merging sibling statuses.@@ -109,8 +161,14 @@ will succeed, especially during the accepted mixed-version window.## Regression coverage-- Actual 332-to-469 migration and replay against an isolated transactional- schema; non-category field preservation and SQL tenant isolation.+- Real runner upgrade tests with pending and applied 469, 478 lock timeout,+ retry/replay, unchanged system/archived rows and released DDL locks. The+ historical 332-to-469 test remains as coverage of the preserved historical SQL.+- Old/mixed/new storage matrices for seven-value legacy groups, explicit+ four-value groups, concrete status groups, per-bucket pagination and counts;+ visible parent lanes, format-bound cursors, cross-workspace isolation and GC.+- 100 historical terminal signals cannot starve a live recovery in another+ workspace; old custom Backlog retains the agreed non-parking semantics.- Built-in identity, custom lifecycle vs special behavior, unknown-key handling,archived status reads, category filtering, table/swimlane grouping.- Old/current category inputs and legacy response encoding, including realtimediff --git a/packages/core/api/issue-table-category-compatibility.test.ts b/packages/core/api/issue-table-category-compatibility.test.tsnew file mode 100644index 0000000000..02e0ac37c8--- /dev/null+++ b/packages/core/api/issue-table-category-compatibility.test.ts@@ -0,0 +1,32 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { parseWithFallback } from "./schema";+import {+ EMPTY_ISSUE_TABLE_GROUPS_RESPONSE,+ IssueTableGroupsResponseSchema,+} from "./schemas";++describe("table category wire compatibility", () => {+ it.each(["in_review", "in_progress", "cancelled", "started", "closed", "custom_qa"])(+ "preserves %s without changing the corresponding group key",+ (status) => {+ const key = `status_category:${status}`;+ const parsed = IssueTableGroupsResponseSchema.parse({+ query_fingerprint: "query",+ total: 2,+ groups: [{ key, count: 2, value: { kind: "status", status } }],+ });+ expect(parsed.groups[0]).toEqual({ key, count: 2, value: { kind: "status", status } });+ },+ );++ it("falls back on malformed group values before UI filtering", () => {+ const parsed = parseWithFallback({+ query_fingerprint: "query", total: 2,+ groups: [{ key: "status_category:started", count: 2, value: { kind: "status", status: null } }],+ }, IssueTableGroupsResponseSchema, EMPTY_ISSUE_TABLE_GROUPS_RESPONSE, {+ endpoint: "POST /api/issues/table/groups",+ });+ expect(parsed).toEqual(EMPTY_ISSUE_TABLE_GROUPS_RESPONSE);+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 9163aade68..0463b071a8 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1376,6 +1376,8 @@ const IssueTableParentRefSchema = z.object({const IssueTableGroupValueSchema = z.discriminatedUnion("kind", [z.object({kind: z.literal("status"),+ // Preserve the requested bucket vocabulary (legacy wire, lifecycle, or+ // concrete status). Normalizing here would disconnect values from keys.status: z.string(),}).loose(),z.object({diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 4651b2b60e..6bfb2f0001 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -340,10 +340,12 @@ export type IssueTableGroupSpec =* Retained for installed clients. New Board/List/Swimlane surfaces group by* concrete status keys, not categories. The descriptor still reports* `value.kind === "status"` for response compatibility; the group KEY is- * what distinguishes lifecycle categories from concrete statuses.+ * what distinguishes category buckets from concrete statuses. By default+ * buckets use the seven-value wire enum; category_format=lifecycle opts into+ * unstarted/started/done/closed.* (MUL-6243)*/- | { kind: "status_category" }+ | { kind: "status_category"; category_format?: "lifecycle" }| { kind: "assignee" }| { kind: "project" }| { kind: "parent" }@@ -352,6 +354,8 @@ export type IssueTableGroupSpec =primary: "assignee" | "project" | "parent";/** `status_category` folds custom statuses into their category's cell. */secondary: "status" | "status_category";+ /** Omit for legacy seven-value category buckets; only for status_category. */+ category_format?: "lifecycle";/** Optional visible secondary buckets. When present, the server pages* only primary groups that contain at least one matching card and* returns `total` for that complete visible result set. */diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 0e3cfa7bfc..44e866ea39 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -409,6 +409,9 @@ func refuseChannelChatRouteHistoryRollbackWith(ctx context.Context, query rowQue}var upMigrationConditions = map[string]migrationCondition{+ // Preserve applied history; pending 469 is superseded by the bounded expand+ // migration. Backfill is an independent operator job, never startup work.+ "469_issue_status_lifecycle_categories": skipMigration("superseded by 478 compatibility expansion; backfill runs separately (MUL-7365)"),// Current search no longer consumes an issue-description GIN. Fresh installs// should not build the historical fallback only to retire it at migration 464."139_issue_description_trgm_index": skipMigration("issue description search indexes are retired by migration 464"),diff --git a/server/cmd/migrate/status_category_expand_test.go b/server/cmd/migrate/status_category_expand_test.gonew file mode 100644index 0000000000..616ffdeee3--- /dev/null+++ b/server/cmd/migrate/status_category_expand_test.go@@ -0,0 +1,126 @@+package main++import (+ "context"+ "os"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/issuestatus"+)++func TestStatusCategoryExpandUpgradePaths(t *testing.T) {+ for _, applied := range []bool{false, true} {+ name := "pending_469"+ if applied {+ name = "applied_469"+ }+ t.Run(name, func(t *testing.T) {+ f := newFixture(t)+ pool := openTestPoolWithSearchPath(t, f.schema)+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)+ defer cancel()+ execFile := func(version string) {+ t.Helper()+ file := realMigrationFiles(t, []string{version}, "up")[0]+ body, err := os.ReadFile(file)+ if err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, string(body)); err != nil {+ t.Fatal(err)+ }+ }+ execFile("332_issue_status")+ for _, key := range issuestatus.Canonical() {+ _, err := pool.Exec(ctx, `INSERT INTO issue_status(workspace_id,key,name,category,color,is_system,archived_at)+ VALUES ('00000000-0000-0000-0000-000000000001',$1,'System',$1,'#123456',true,NULL),+ ('00000000-0000-0000-0000-000000000001','custom_' || $1,'Custom',$1,'#123456',false,now())`, key)+ if err != nil {+ t.Fatal(err)+ }+ }+ opts := f.opts()+ opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories"}, "up")+ if applied {+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatal(err)+ }+ }+ var before string+ if err := pool.QueryRow(ctx, `SELECT jsonb_agg(to_jsonb(s) ORDER BY key)::text FROM issue_status s`).Scan(&before); err != nil {+ t.Fatal(err)+ }+ opts.Files = realMigrationFiles(t, []string{"469_issue_status_lifecycle_categories", "477_issue_effective_status_triage", "478_issue_status_category_expand"}, "up")+ opts.Conditions = conditionsForDirection("up")+ if !applied {+ // A normal reader prevents the expand DDL. The real runner must time out,+ // leave all rows intact, and not record 478 as applied.+ reader, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer reader.Rollback(context.Background())+ if _, err := reader.Exec(ctx, "SELECT * FROM issue_status"); err != nil {+ t.Fatal(err)+ }+ start := time.Now()+ err = runMigrations(ctx, pool, opts)+ if err == nil || !strings.Contains(err.Error(), "lock timeout") {+ t.Fatalf("expected bounded lock timeout, got %v", err)+ }+ t.Logf("reader contention stopped expand after %s", time.Since(start))+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, "478_issue_status_category_expand", false)+ if err := reader.Rollback(ctx); err != nil {+ t.Fatal(err)+ }+ }+ for range 2 {+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatal(err)+ }+ }+ // Also replay the actual SQL after an uncertain ledger acknowledgement.+ execFile("478_issue_status_category_expand")+ var after string+ if err := pool.QueryRow(ctx, `SELECT jsonb_agg(to_jsonb(s) ORDER BY key)::text FROM issue_status s`).Scan(&after); err != nil {+ t.Fatal(err)+ }+ if after != before {+ t.Fatal("expand rewrote catalog rows, identity or archived data")+ }+ for _, key := range issuestatus.Canonical() {+ want := "custom_" + key+ if key == "done" || key == "cancelled" {+ want = key+ }+ var got string+ if err := pool.QueryRow(ctx, `SELECT issue_effective_status('00000000-0000-0000-0000-000000000001',$1)`, "custom_"+key).Scan(&got); err != nil {+ t.Fatal(err)+ }+ if got != want {+ t.Fatalf("%s behavior = %s, want %s", key, got, want)+ }+ }+ var locks int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM pg_locks WHERE relation = 'issue_status'::regclass AND mode = 'AccessExclusiveLock'`).Scan(&locks); err != nil {+ t.Fatal(err)+ }+ if locks != 0 {+ t.Fatalf("expand retained %d exclusive locks", locks)+ }+ t.Log("14 system/archived rows unchanged; no exclusive locks remain; replay passed")+ // Both old and new writes remain legal while readers are upgraded.+ if _, err := pool.Exec(ctx, `UPDATE issue_status SET category = 'cancelled' WHERE key = 'custom_cancelled';+ UPDATE issue_status SET category = 'closed' WHERE key = 'custom_cancelled'`); err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, `UPDATE issue_status SET category = 'started' WHERE key = 'cancelled'`); err == nil {+ t.Fatal("noncanonical built-in pair accepted")+ }+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, "469_issue_status_lifecycle_categories", true)+ assertMigrationVersionRecorded(t, ctx, pool, f.schema, "478_issue_status_category_expand", true)+ })+ }+}diff --git a/server/internal/handler/daemon_claim_issue_status_test.go b/server/internal/handler/daemon_claim_issue_status_test.goindex 40ef93a8db..24d61f81b4 100644--- a/server/internal/handler/daemon_claim_issue_status_test.go+++ b/server/internal/handler/daemon_claim_issue_status_test.go@@ -28,6 +28,12 @@ func TestClaimTaskByRuntime_PopulatesIssueStatusCatalog(t *testing.T) {createTestCustomStatus(t, "awaiting_response", "started")createTestCustomStatus(t, "accepted", "done")createTestCustomStatus(t, "withdrawn", "closed")+ // The catalog remains mixed until the independent backfill runs. The wire+ // contract (and its ordering) must not depend on whether a row was converted.+ dbfx.Exec(t, `UPDATE issue_status SET category = CASE key+ WHEN 'rework' THEN 'todo' WHEN 'awaiting_response' THEN 'in_review'+ WHEN 'withdrawn' THEN 'cancelled' ELSE category END+ WHERE workspace_id = $1 AND key IN ('rework', 'awaiting_response', 'withdrawn')`, testWorkspaceID)dbfx.Exec(t, `UPDATE issue_status SET description = 'Custom guidance' WHERE workspace_id = $1 AND key IN ('awaiting_response', 'accepted', 'withdrawn')`, testWorkspaceID)// A different workspace's catalog must never enter this claim.otherWorkspace := dbfx.Workspace(t, "Other catalog", "other-claim-catalog")diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.goindex 7d1125005d..98e9685759 100644--- a/server/internal/handler/issue_status.go+++ b/server/internal/handler/issue_status.go@@ -597,7 +597,7 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {}active := make([]db.IssueStatus, 0, len(catalog))for _, entry := range catalog {- if entry.Category == category && (req.IncludeSystem || !entry.IsSystem) {+ if normalized, _ := issuestatus.ParseCategory(entry.Category); normalized == category && (req.IncludeSystem || !entry.IsSystem) {active = append(active, entry)}}@@ -627,7 +627,7 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusForbidden, "include_system is required to reorder built-in statuses")case entry.ArchivedAt.Valid:writeError(w, http.StatusConflict, "archived statuses cannot be reordered")- case entry.Category != category:+ case normalizedStatusCategory(entry.Category) != category:writeError(w, http.StatusBadRequest, "ids must all belong to the requested category")default:writeError(w, http.StatusConflict, "issue status catalog changed during reorder")@@ -698,3 +698,8 @@ func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {"total": len(resp),})}++func normalizedStatusCategory(category string) string {+ normalized, _ := issuestatus.ParseCategory(category)+ return normalized+}diff --git a/server/internal/handler/issue_status_compatibility_test.go b/server/internal/handler/issue_status_compatibility_test.gonew file mode 100644index 0000000000..c0e1f4ec86--- /dev/null+++ b/server/internal/handler/issue_status_compatibility_test.go@@ -0,0 +1,246 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "slices"+ "testing"++ "github.com/google/uuid"+ "github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// These are the installed Web/Desktop consumer's literal accepted buckets,+// deliberately independent of the server's current category constants.+var installedStatusBuckets = []string{"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"}++func TestStatusCompatibilityMixedStorageGroupsAndPagination(t *testing.T) {+ for _, storage := range []string{"old", "mixed", "new"} {+ t.Run(storage, func(t *testing.T) {+ project := dbfx.Insert(t, "project", testutil.Cols{"workspace_id": testWorkspaceID, "title": "Compatibility " + storage})+ suffix := uuid.NewString()[:8]+ expectedWire := map[string]string{}+ expectedLifecycle := map[string]string{}+ for i, old := range installedStatusBuckets {+ category, _ := issuestatus.CategoryForBehavior(old)+ stored := category+ if storage == "old" || (storage == "mixed" && i%2 == 0) {+ stored = old+ }+ key := fmt.Sprintf("compat_%s_%d", suffix, i)+ cols := testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": stored, "color": "#123456"}+ if old == "cancelled" {+ cols["archived_at"] = testutil.Raw("now()")+ }+ dbfx.Insert(t, "issue_status", cols)+ for _, status := range []string{key, old} {+ dbfx.Issue(t, status, testutil.Cols{"status": status, "project_id": project})+ expectedWire[status] = issuestatus.WireCategory(status, category)+ expectedLifecycle[status] = category+ }+ keys, err := issuestatus.ExpandCategories(context.Background(), testHandler.Queries, parseUUID(testWorkspaceID), []string{category})+ if err != nil || !slices.Contains(keys, key) {+ t.Fatalf("category filter dropped %s: %v, %v", key, keys, err)+ }+ }+ query := statusCategoryQuery(project)+ for _, spec := range []issueTableGroupSpec{+ {Kind: "status_category"},+ {Kind: "compound", Primary: "project", Secondary: "status_category"},+ {Kind: "status_category", CategoryFormat: "lifecycle"},+ {Kind: "compound", Primary: "project", Secondary: "status_category", CategoryFormat: "lifecycle"},+ {Kind: "status"},+ } {+ t.Run(spec.Kind+"/"+spec.CategoryFormat, func(t *testing.T) {+ var groups issueTableGroupsResponse+ testutil.Call(t, testHandler.ListIssueTableGroups, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{+ Query: query, Group: spec, Page: issueTablePageRequest{Limit: 100},+ })).Want(http.StatusOK).JSON(&groups)+ if groups.Total != 14 {+ t.Fatalf("total=%d, want 14", groups.Total)+ }+ cells := groups.Groups+ if spec.Kind == "compound" {+ if len(cells) != 1 {+ t.Fatalf("lanes=%d", len(cells))+ }+ cells = cells[0].SecondaryGroups+ }+ seen := map[string]bool{}+ for _, cell := range cells {+ legacy := spec.Kind != "status" && spec.CategoryFormat == ""+ if legacy && !slices.Contains(installedStatusBuckets, cell.Value.Status) {+ t.Fatalf("installed consumer hides %q", cell.Value.Status)+ }+ var cursor *string+ var count int64+ for page := 0; page < 20; page++ {+ var rows issueTableRowsResponse+ testutil.Call(t, testHandler.ListIssueTableRows, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{+ Query: query, Group: spec, GroupKey: &cell.Key, Page: issueTablePageRequest{Limit: 1, Cursor: cursor},+ })).Want(http.StatusOK).JSON(&rows)+ for _, row := range rows.Rows {+ status := row.Issue.Status+ if seen[status] {+ t.Fatalf("duplicate paged card: %s", status)+ }+ seen[status] = true+ want := status+ if legacy {+ want = expectedWire[status]+ } else if spec.Kind != "status" {+ want = expectedLifecycle[status]+ }+ if cell.Value.Status != want {+ t.Fatalf("card %s belongs to %s, got %s", status, want, cell.Value.Status)+ }+ if row.Issue.StatusCategory != expectedWire[status] {+ t.Fatalf("row category drift for %s: %s", status, row.Issue.StatusCategory)+ }+ count+++ }+ cursor = rows.NextCursor+ if cursor == nil {+ break+ }+ if page == 19 {+ t.Fatal("pagination did not terminate")+ }+ }+ if count != cell.Count {+ t.Fatalf("bucket %s: header=%d rows=%d", cell.Value.Status, cell.Count, count)+ }+ }+ if len(seen) != 14 {+ t.Fatalf("visible cards=%d, want 14", len(seen))+ }+ })+ }+ // A legacy client can show only In Review: it must not acquire the+ // In Progress/Blocked cards merely because all share lifecycle Started.+ var filtered issueTableGroupsResponse+ testutil.Call(t, testHandler.ListIssueTableGroups, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{+ Query: query, Group: issueTableGroupSpec{Kind: "compound", Primary: "project", Secondary: "status_category", SecondaryValues: []string{"in_review"}}, Page: issueTablePageRequest{Limit: 1},+ })).Want(http.StatusOK).JSON(&filtered)+ if filtered.Total != 1 {+ t.Fatalf("visible In Review cards=%d, want 1", filtered.Total)+ }+ })+ }+}++func TestStatusCompatibilityCatalogWritesAndTenantIsolation(t *testing.T) {+ ctx := context.Background()+ key := "legacy_" + uuid.NewString()[:8]+ id := dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "in_review", "color": "#123456", "position": 99999})+ // Position allocation includes the old spelling in the same lifecycle.+ created, err := testHandler.Queries.CreateIssueStatusEntry(ctx, db.CreateIssueStatusEntryParams{+ WorkspaceID: parseUUID(testWorkspaceID), Key: key + "_new", Name: "New", Category: "started", Color: "#123456",+ })+ if err != nil {+ t.Fatal(err)+ }+ dbfx.Cleanup(t, "DELETE FROM issue_status WHERE id=$1", created.ID)+ if created.Position != 100000 {+ t.Fatalf("new position=%v, want 100000", created.Position)+ }+ catalog, err := testHandler.Queries.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{WorkspaceID: parseUUID(testWorkspaceID)})+ if err != nil {+ t.Fatal(err)+ }+ ids := []string{}+ for _, entry := range catalog {+ if normalizedStatusCategory(entry.Category) == "started" && !entry.IsSystem {+ ids = append(ids, uuid.UUID(entry.ID.Bytes).String())+ }+ }+ testutil.Call(t, testHandler.ReorderIssueStatuses, newRequest(http.MethodPost, "/api/issue-statuses/reorder", ReorderIssueStatusesRequest{Category: "in_review", IDs: ids})).Want(http.StatusOK)+ var stored string+ dbfx.QueryRow(t, "SELECT category FROM issue_status WHERE id=$1", id).Scan(&stored)+ if stored != "started" {+ t.Fatalf("reorder retained old category %s", stored)+ }+ foreign := dbfx.Workspace(t, "Other", "compat-"+uuid.NewString()[:8])+ foreignKey := "foreign_" + uuid.NewString()[:8]+ dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": foreign, "key": foreignKey, "name": "Foreign", "category": "cancelled", "color": "#123456"})+ keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, parseUUID(testWorkspaceID), []string{"closed"})+ if err != nil || slices.Contains(keys, foreignKey) {+ t.Fatalf("cross-workspace filter expansion: %v, %v", keys, err)+ }+ if got := issuestatus.Effective(ctx, testHandler.Queries, parseUUID(testWorkspaceID), foreignKey); got != foreignKey {+ t.Fatalf("cross-workspace terminal behavior: %s", got)+ }+}++func TestStatusCompatibilityGCBeforeAndAfterBackfill(t *testing.T) {+ for _, old := range installedStatusBuckets {+ category, _ := issuestatus.CategoryForBehavior(old)+ for _, stored := range []string{old, category} {+ t.Run(old+"/"+stored, func(t *testing.T) {+ key := "gc_" + uuid.NewString()[:8]+ dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": stored, "color": "#123456"})+ id := dbfx.Issue(t, key, testutil.Cols{"status": key})+ type result struct {+ Status string `json:"status"`+ Category string `json:"category"`+ }+ check := func(got result) {+ t.Helper()+ if got.Status != issuestatus.WireCategory(key, category) || got.Category != category {+ t.Fatalf("GC wire=%+v for stored %s", got, stored)+ }+ }+ var single result+ req := withURLParam(newDaemonTokenRequest("GET", "/api/daemon/issues/"+id+"/gc-check", nil, testWorkspaceID, "compat-daemon"), "issueId", id)+ testutil.Call(t, testHandler.GetIssueGCCheck, req).Want(http.StatusOK).JSON(&single)+ check(single)+ var batch struct {+ Issues []result `json:"issues"`+ }+ req = withURLParam(newDaemonTokenRequest("POST", "/api/daemon/workspaces/"+testWorkspaceID+"/issues/gc-check", map[string]any{"issue_ids": []string{id}}, testWorkspaceID, "compat-daemon"), "workspaceId", testWorkspaceID)+ testutil.Call(t, testHandler.BatchIssueGCCheck, req).Want(http.StatusOK).JSON(&batch)+ if len(batch.Issues) != 1 {+ t.Fatalf("GC results=%d", len(batch.Issues))+ }+ check(batch.Issues[0])+ })+ }+ }+}++func TestStatusCompatibilityCursorRejectsDifferentCategoryFormat(t *testing.T) {+ project, _ := seedStatusCategoryFixture(t)+ key := "status_category:in_progress"+ request := issueTableRowsRequest{Query: statusCategoryQuery(project), Group: issueTableGroupSpec{Kind: "status_category"}, GroupKey: &key, Page: issueTablePageRequest{Limit: 1}}+ var rows issueTableRowsResponse+ testutil.Call(t, testHandler.ListIssueTableRows, newRequest(http.MethodPost, "/api/issues/table/rows", request)).Want(http.StatusOK).JSON(&rows)+ if rows.NextCursor == nil {+ t.Fatal("expected a second legacy page")+ }+ request.Page.Cursor = rows.NextCursor+ request.Group.CategoryFormat = "lifecycle"+ testutil.Call(t, testHandler.ListIssueTableRows, newRequest(http.MethodPost, "/api/issues/table/rows", request)).Want(http.StatusConflict)+}++func TestStatusCompatibilityParentLaneUsesExpandedVisibleKeys(t *testing.T) {+ project := dbfx.Insert(t, "project", testutil.Cols{"workspace_id": testWorkspaceID, "title": "Category parent lane"})+ key := "child_" + uuid.NewString()[:8]+ dbfx.Insert(t, "issue_status", testutil.Cols{"workspace_id": testWorkspaceID, "key": key, "name": key, "category": "in_review", "color": "#123456"})+ parent := dbfx.Issue(t, "Parent", testutil.Cols{"project_id": project, "status": "in_progress"})+ dbfx.Issue(t, "Child", testutil.Cols{"project_id": project, "status": key, "parent_issue_id": parent})+ group := issueTableGroupSpec{Kind: "compound", Primary: "parent", Secondary: "status_category", SecondaryValues: []string{"in_progress"}}+ var groups issueTableGroupsResponse+ testutil.Call(t, testHandler.ListIssueTableGroups, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{Query: statusCategoryQuery(project), Group: group, Page: issueTablePageRequest{Limit: 10}})).Want(http.StatusOK).JSON(&groups)+ if groups.Total != 1 || len(groups.Groups) != 1 || groups.Groups[0].Key != "parent:"+parent {+ t.Fatalf("visible parent groups = %+v", groups)+ }+ noParent := compoundCellGroupKey("parent:none", "in_progress", true)+ var rows issueTableRowsResponse+ testutil.Call(t, testHandler.ListIssueTableRows, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{Query: statusCategoryQuery(project), Group: group, GroupKey: &noParent, Page: issueTablePageRequest{Limit: 10}})).Want(http.StatusOK).JSON(&rows)+ if len(rows.Rows) != 0 {+ t.Fatalf("promoted parent duplicated in No parent: %+v", rows.Rows)+ }+}diff --git a/server/internal/handler/issue_table_group.go b/server/internal/handler/issue_table_group.goindex 95c4c49e3d..94bf3db008 100644--- a/server/internal/handler/issue_table_group.go+++ b/server/internal/handler/issue_table_group.go@@ -59,6 +59,7 @@ type issueTableGroupsResponse struct {}type resolvedIssueTableGroup struct {+ legacyCategories boolkind stringpropertyID stringpropertyType string@@ -131,16 +132,24 @@ func statusOrderExpression(categoryExpr string) string {func (h *Handler) resolveStatusCategoryMaps(ctx context.Context,workspaceID pgtype.UUID,+ legacy bool,) (customKeys map[string]string, categoryKeys map[string][]string, err error) {customKeys, err = issuestatus.CustomKeyCategories(ctx, h.issueStatusCatalog(), workspaceID)if err != nil {return nil, nil, err}categoryKeys = make(map[string][]string, len(validIssueStatusCategories))- for _, category := range validIssueStatusCategories {+ categories := validIssueStatusCategories+ if legacy {+ categories = validIssueStatuses+ }+ for _, category := range categories {// Every category contains its built-in behaviors even for an unseeded// workspace.categoryKeys[category] = issuestatus.BehaviorsForCategory(category)+ if legacy {+ categoryKeys[category] = []string{category}+ }}// Sorted so the expansion — and therefore the query's argument list — is// deterministic for the same catalog.@@ -151,12 +160,30 @@ func (h *Handler) resolveStatusCategoryMaps(sort.Strings(keys)for _, key := range keys {category := customKeys[key]+ if legacy {+ category = issuestatus.WireCategory(key, category)+ customKeys[key] = category+ }categoryKeys[category] = append(categoryKeys[category], key)}return customKeys, categoryKeys, nil}func issueTableGroupIdentity(group issueTableGroupSpec) string {+ identity := issueTableGroupBaseIdentity(group)+ if group.Kind == "status_category" || (group.Kind == "compound" && group.Secondary == "status_category") {+ format := group.CategoryFormat+ if format == "" {+ format = "legacy"+ }+ // Do not accept cursors minted before the category wire contract was+ // explicit, or cursors from the other format.+ return identity + ":category_format=" + format+ }+ return identity+}++func issueTableGroupBaseIdentity(group issueTableGroupSpec) string {if group.Kind == "property" {return "group:property:" + group.PropertyID + ":empty=" + strconv.FormatBool(group.IncludeEmpty)}@@ -171,6 +198,12 @@ func issueTableGroupIdentity(group issueTableGroupSpec) string {}func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request, workspaceID pgtype.UUID, group issueTableGroupSpec, allowNone bool) (resolvedIssueTableGroup, bool) {+ if group.CategoryFormat != "" && (group.CategoryFormat != "lifecycle" ||+ (group.Kind != "status_category" && !(group.Kind == "compound" && group.Secondary == "status_category"))) {+ writeError(w, http.StatusBadRequest, "category_format=lifecycle requires status_category grouping")+ return resolvedIssueTableGroup{}, false+ }+ legacy := group.CategoryFormat == ""if group.Kind != "compound" && group.SecondaryValues != nil {writeError(w, http.StatusBadRequest, "group.secondary_values requires group.kind=compound")return resolvedIssueTableGroup{}, false@@ -206,7 +239,7 @@ func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request,case "status_category":// Retained category-grouping API for installed clients. New task views// use exact status groups, including custom keys.- customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID)+ customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID, legacy)if err != nil {slog.Warn("resolve status category group failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to resolve table group")@@ -214,6 +247,7 @@ func (h *Handler) resolveIssueTableGroup(w http.ResponseWriter, r *http.Request,}return resolvedIssueTableGroup{kind: "status_category",+ legacyCategories: legacy,categoryKeys: categoryKeys,statusCustomKeys: customKeys,}, true@@ -271,7 +305,7 @@ END, ''))`,seenInputs := make(map[string]bool, len(group.SecondaryValues))normalizedSecondaryValues := make([]string, 0, len(group.SecondaryValues))validSecondary := validIssueStatuses- if secondaryCategory {+ if secondaryCategory && !legacy {validSecondary = validIssueStatusCategories}for _, value := range group.SecondaryValues {@@ -280,7 +314,7 @@ END, ''))`,return resolvedIssueTableGroup{}, false}seenInputs[value] = true- if secondaryCategory {+ if secondaryCategory && !legacy {if normalized, ok := issuestatus.ParseCategory(value); ok {value = normalized}@@ -306,10 +340,11 @@ END, ''))`,secondaryValues: normalizedSecondaryValues,secondaryFiltered: group.SecondaryValues != nil,secondaryCategory: secondaryCategory,+ legacyCategories: legacy,statusCustomKeys: customKeys,}if secondaryCategory {- customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID)+ customKeys, categoryKeys, err := h.resolveStatusCategoryMaps(r.Context(), workspaceID, legacy)if err != nil {slog.Warn("resolve compound status category group failed", append(logger.RequestAttrs(r), "error", err)...)writeIssueTableQueryFailure(w, r, "failed to resolve table group")@@ -394,7 +429,7 @@ func (group resolvedIssueTableGroup) expression(addArg func(any) string) stringreturn group.primary.expression(addArg)}if group.kind == "status_category" {- return statusCategoryExpr(group.statusCustomKeys, addArg)+ return group.categoryExpression(addArg)}if group.kind == "property" && group.propertyType == "select" {active := make([]string, 0, len(group.activeOptions))@@ -436,6 +471,8 @@ func issueTableStatusOrder(entries []db.IssueStatus) []string {categoryRank := map[string]int{"unstarted": 0, "started": 1, "done": 2, "closed": 3}sort.Slice(rows, func(i, j int) bool {a, b := rows[i], rows[j]+ a.Category, _ = issuestatus.ParseCategory(a.Category)+ b.Category, _ = issuestatus.ParseCategory(b.Category)if categoryRank[a.Category] != categoryRank[b.Category] {return categoryRank[a.Category] < categoryRank[b.Category]}@@ -465,6 +502,9 @@ func (group resolvedIssueTableGroup) orderExpression(addArg func(any) string) stcase "status":return fmt.Sprintf("COALESCE(array_position(%s::text[], group_value), 100000)", addArg(group.statusOrder))case "status_category":+ if group.legacyCategories {+ return fmt.Sprintf("COALESCE(array_position(%s::text[], group_value), 100000)", addArg(validIssueStatuses))+ }return statusOrderExpression("group_value")case "assignee":return "CASE split_part(group_value, ':', 1) WHEN 'member' THEN 0 WHEN 'agent' THEN 1 WHEN 'squad' THEN 2 ELSE 3 END"@@ -525,6 +565,9 @@ func (group resolvedIssueTableGroup) categoryKeysFor(category string) []string {if keys := group.categoryKeys[category]; len(keys) > 0 {return keys}+ if group.legacyCategories {+ return []string{category}+ }return issuestatus.BehaviorsForCategory(category)}@@ -551,7 +594,7 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64, contextsort.Strings(customKeys)secondaryValues = append(secondaryValues, customKeys...)if group.secondaryCategory {- secondaryValues = validIssueStatusCategories+ secondaryValues = group.categoryValues()}for _, status := range secondaryValues {statusCount := secondaryCounts[status]@@ -579,7 +622,7 @@ func (group resolvedIssueTableGroup) descriptor(raw string, count int64, contextdescriptor.Key = "status:" + rawdescriptor.Value = issueTableGroupValueResponse{Kind: "status", Status: raw}case "status_category":- if !issueTableContainsString(validIssueStatusCategories, raw) {+ if !issueTableContainsString(group.categoryValues(), raw) {return descriptor, fmt.Errorf("unexpected status category group value %q", raw)}descriptor.Key = statusCategoryGroupKey(raw)@@ -684,8 +727,8 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key stringencoded, status, ok := strings.Cut(encodedAndStatus, axis)validSecondary := validIssueStatusesif group.secondaryCategory {- validSecondary = validIssueStatusCategories- if normalized, valid := issuestatus.ParseCategory(status); valid {+ validSecondary = group.categoryValues()+ if normalized, valid := issuestatus.ParseCategory(status); valid && !group.legacyCategories {status = normalized}}@@ -728,6 +771,10 @@ func (group resolvedIssueTableGroup) predicate(w http.ResponseWriter, key stringreturn fmt.Sprintf("i.status = %s::text", addArg(status)), truecase "status_category":category, ok := parseStatusCategoryGroupKey(key)+ if group.legacyCategories {+ category, ok = strings.CutPrefix(key, statusCategoryGroupKeyPrefix)+ ok = ok && issueTableContainsString(group.categoryValues(), category)+ }if !ok {writeError(w, http.StatusBadRequest, "invalid group_key")return "", false@@ -950,7 +997,7 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {// of the column it renders in, never a cell of its own. (MUL-6243)secondaryExpr := "i.status"if group.secondaryCategory {- secondaryExpr = statusCategoryExpr(group.statusCustomKeys, addArg)+ secondaryExpr = group.categoryExpression(addArg)}groupedCTE = fmt.Sprintf(`cells AS (SELECT %s AS group_value, %s AS secondary_value, COUNT(*)::bigint AS cell_count@@ -971,7 +1018,7 @@ func (h *Handler) ListIssueTableGroups(w http.ResponseWriter, r *http.Request) {// to expand back to concrete keys there; the cell filters compare// against secondary_value, which is already a category.visibleKeysRef := visibleRef- if group.secondaryCategory {+ if group.secondaryCategory && group.primary != nil && group.primary.kind == "parent" {expanded := make([]string, 0, len(group.secondaryValues))for _, category := range group.secondaryValues {expanded = append(expanded, group.categoryKeysFor(category)...)@@ -1126,3 +1173,27 @@ func (h *Handler) issueStatusCatalog() issuestatus.Querier {}return h.Queries}++// A legacy category bucket must match the per-row wire category, including+// built-in identity. Lifecycle grouping is an explicit request capability.+func (group resolvedIssueTableGroup) categoryValues() []string {+ if group.legacyCategories {+ return validIssueStatuses+ }+ return validIssueStatusCategories+}++func (group resolvedIssueTableGroup) categoryExpression(addArg func(any) string) string {+ if !group.legacyCategories {+ return statusCategoryExpr(group.statusCustomKeys, addArg)+ }+ keys := make(map[string]string, len(group.statusCustomKeys)+len(validIssueStatuses))+ for key, category := range group.statusCustomKeys {+ keys[key] = category+ }+ for _, key := range validIssueStatuses {+ keys[key] = key+ }+ // Explicit built-in entries override the lifecycle defaults in the helper.+ return statusCategoryExpr(keys, addArg)+}diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 8820a8a2f8..bec5db5c70 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -81,21 +81,21 @@ type issueTableDateFilterRequest struct {}type issueTableFiltersRequest struct {- Statuses []string `json:"statuses,omitempty"`- Priorities []string `json:"priorities,omitempty"`- Assignees []issueTableActorRef `json:"assignees,omitempty"`- IncludeNoAssignee bool `json:"include_no_assignee,omitempty"`- Creators []issueTableActorRef `json:"creators,omitempty"`- ProjectIDs []string `json:"project_ids,omitempty"`- IncludeNoProject bool `json:"include_no_project,omitempty"`- LabelIDs []string `json:"label_ids,omitempty"`+ Statuses []string `json:"statuses,omitempty"`+ Priorities []string `json:"priorities,omitempty"`+ Assignees []issueTableActorRef `json:"assignees,omitempty"`+ IncludeNoAssignee bool `json:"include_no_assignee,omitempty"`+ Creators []issueTableActorRef `json:"creators,omitempty"`+ ProjectIDs []string `json:"project_ids,omitempty"`+ IncludeNoProject bool `json:"include_no_project,omitempty"`+ LabelIDs []string `json:"label_ids,omitempty"`// Members are raw JSON so operator objects ({op, value}) and plain// strings both survive the round-trip into parsePropertiesFilterParam.- Properties map[string][]json.RawMessage `json:"properties,omitempty"`- Date *issueTableDateFilterRequest `json:"date,omitempty"`- WorkingOnly bool `json:"working_only,omitempty"`- WorkingIssueIDs []string `json:"working_issue_ids,omitempty"`- IncludeSubIssues *bool `json:"include_sub_issues,omitempty"`+ Properties map[string][]json.RawMessage `json:"properties,omitempty"`+ Date *issueTableDateFilterRequest `json:"date,omitempty"`+ WorkingOnly bool `json:"working_only,omitempty"`+ WorkingIssueIDs []string `json:"working_issue_ids,omitempty"`+ IncludeSubIssues *bool `json:"include_sub_issues,omitempty"`}type issueTableSortRequest struct {@@ -111,6 +111,8 @@ type issueTableQuerySpec struct {}type issueTableGroupSpec struct {+ // Empty preserves the seven-value protocol used by installed clients.+ CategoryFormat string `json:"category_format,omitempty"`Kind string `json:"kind"`PropertyID string `json:"property_id,omitempty"`IncludeEmpty bool `json:"include_empty,omitempty"`diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex 72aa2125f2..a97cc396b9 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -352,7 +352,14 @@ func (h *Handler) ListIssueTableRows(w http.ResponseWriter, r *http.Request) {group.primary != nil &&group.primary.kind == "parent" &&group.secondaryFiltered {- visibleRef := addArg(group.secondaryValues)+ visibleKeys := group.secondaryValues+ if group.secondaryCategory {+ visibleKeys = nil+ for _, category := range group.secondaryValues {+ visibleKeys = append(visibleKeys, group.categoryKeysFor(category)...)+ }+ }+ visibleRef := addArg(visibleKeys)ctePrefix += fmt.Sprintf(`membership AS NOT MATERIALIZED (SELECT i.*FROM issue idiff --git a/server/internal/handler/issue_table_status_category_test.go b/server/internal/handler/issue_table_status_category_test.goindex 7aaede5a10..f335307315 100644--- a/server/internal/handler/issue_table_status_category_test.go+++ b/server/internal/handler/issue_table_status_category_test.go@@ -79,7 +79,7 @@ func TestIssueTableAcceptsLegacyLifecycleGroupInputs(t *testing.T) {legacyKey := "status_category:in_review"w := httptest.NewRecorder()testHandler.ListIssueTableRows(w, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{- Query: statusCategoryQuery(projectID), Group: issueTableGroupSpec{Kind: "status_category"},+ Query: statusCategoryQuery(projectID), Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},GroupKey: &legacyKey, Page: issueTablePageRequest{Limit: 50},}))if w.Code != http.StatusOK {@@ -97,7 +97,7 @@ func TestIssueTableAcceptsLegacyLifecycleGroupInputs(t *testing.T) {// rejected by the existing validation contract.w = httptest.NewRecorder()group, ok := testHandler.resolveIssueTableGroup(w, newRequest(http.MethodPost, "/api/issues/table/groups", nil), parseUUID(testWorkspaceID), issueTableGroupSpec{- Kind: "compound", Primary: "project", Secondary: "status_category",+ Kind: "compound", Primary: "project", Secondary: "status_category", CategoryFormat: "lifecycle",SecondaryValues: []string{"in_progress", "in_review", "blocked"},}, false)if !ok {@@ -118,7 +118,7 @@ func TestIssueTableStatusCategoryGroupsFoldCustomStatuses(t *testing.T) {w := httptest.NewRecorder()testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{Query: statusCategoryQuery(projectID),- Group: issueTableGroupSpec{Kind: "status_category"},+ Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},Page: issueTablePageRequest{Limit: 100},}))if w.Code != http.StatusOK {@@ -155,7 +155,7 @@ func TestIssueTableStatusCategoryRowsReturnCustomStatusIssues(t *testing.T) {w := httptest.NewRecorder()testHandler.ListIssueTableRows(w, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{Query: statusCategoryQuery(projectID),- Group: issueTableGroupSpec{Kind: "status_category"},+ Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},GroupKey: &groupKey,Page: issueTablePageRequest{Limit: 50},}))@@ -200,7 +200,7 @@ func TestIssueTableCompoundStatusCategoryCellsFoldCustomStatuses(t *testing.T) {Group: issueTableGroupSpec{Kind: "compound",Primary: "project",- Secondary: "status_category",+ Secondary: "status_category", CategoryFormat: "lifecycle",},Page: issueTablePageRequest{Limit: 100},}))@@ -236,7 +236,7 @@ func TestIssueTableCompoundStatusCategoryCellsFoldCustomStatuses(t *testing.T) {Group: issueTableGroupSpec{Kind: "compound",Primary: "project",- Secondary: "status_category",+ Secondary: "status_category", CategoryFormat: "lifecycle",},GroupKey: &cellKey,Page: issueTablePageRequest{Limit: 50},@@ -290,7 +290,7 @@ func TestIssueTableStatusCategoryFoldsBuiltInsWithoutCustomStatuses(t *testing.Tw := httptest.NewRecorder()testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{Query: statusCategoryQuery(projectID),- Group: issueTableGroupSpec{Kind: kind},+ Group: issueTableGroupSpec{Kind: kind, CategoryFormat: "lifecycle"},Page: issueTablePageRequest{Limit: 100},}))if w.Code != http.StatusOK {@@ -376,7 +376,7 @@ func TestIssueTableStatusCategoryReadsCatalogOncePerRequest(t *testing.T) {w := httptest.NewRecorder()testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{Query: statusCategoryQuery(projectID),- Group: issueTableGroupSpec{Kind: "status_category"},+ Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},Page: issueTablePageRequest{Limit: 100},}))if w.Code != http.StatusOK {@@ -405,7 +405,7 @@ func TestIssueTableCompoundStatusCategoryReadsCatalogOncePerRequest(t *testing.TGroup: issueTableGroupSpec{Kind: "compound",Primary: "project",- Secondary: "status_category",+ Secondary: "status_category", CategoryFormat: "lifecycle",},Page: issueTablePageRequest{Limit: 100},}))@@ -535,7 +535,7 @@ func TestIssueTableFiltersAcceptCustomStatusKeys(t *testing.T) {w := httptest.NewRecorder()testHandler.ListIssueTableGroups(w, newRequest(http.MethodPost, "/api/issues/table/groups", issueTableGroupsRequest{Query: query,- Group: issueTableGroupSpec{Kind: "status_category"},+ Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},Page: issueTablePageRequest{Limit: 100},}))if w.Code != http.StatusOK {@@ -553,7 +553,7 @@ func TestIssueTableFiltersAcceptCustomStatusKeys(t *testing.T) {rowsRecorder := httptest.NewRecorder()testHandler.ListIssueTableRows(rowsRecorder, newRequest(http.MethodPost, "/api/issues/table/rows", issueTableRowsRequest{Query: query,- Group: issueTableGroupSpec{Kind: "status_category"},+ Group: issueTableGroupSpec{Kind: "status_category", CategoryFormat: "lifecycle"},GroupKey: &groupKey,Page: issueTablePageRequest{Limit: 50},}))diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.goindex 20e77244eb..ce2dba9caf 100644--- a/server/internal/issuestatus/issuestatus.go+++ b/server/internal/issuestatus/issuestatus.go@@ -196,7 +196,7 @@ func BehaviorsForCategory(category string) []string {}}-// ParseCategory accepts previous API enum spellings at the boundary only.+// ParseCategory normalizes API spellings and pre-backfill stored categories.//// Triage is refused: CategoryForBehavior answers for it so a Triage issue can// still be rendered and grouped, but it is not a category a caller may name —@@ -223,6 +223,9 @@ func ParseCategory(value string) (string, bool) {// clients. This is a presentation adapter, NEVER an execution policy. New clients// normalize it into four lifecycle categories. No legacy behavior is persisted.func WireCategory(status, category string) string {+ if normalized, ok := ParseCategory(category); ok {+ category = normalized+ }if IsBuiltIn(status) {return status}@@ -243,6 +246,7 @@ func WireCategory(status, category string) string {// Custom statuses inherit only terminal lifecycle semantics, not parked, review,// blocked or active-agent recovery behavior. Nonterminal keys stay distinct.func customBehavior(status, category string) string {+ category, _ = ParseCategory(category)switch category {case CategoryDone:return Done@@ -480,10 +484,8 @@ func CategoryAndName(ctx context.Context, q Querier, workspaceID pgtype.UUID, stif err != nil {return "", ""}- if !IsCategory(entry.Category) {- return "", entry.Name- }- return entry.Category, entry.Name+ category, _ := ParseCategory(entry.Category)+ return category, entry.Name}// Resolve validates that status is usable in this workspace, returning the@@ -650,7 +652,7 @@ func (r *Resolver) load(ctx context.Context, q Querier) {r.categories = make(map[string]string, len(entries))r.names = make(map[string]string, len(entries))for _, e := range entries {- r.categories[e.Key] = e.Category+ r.categories[e.Key], _ = ParseCategory(e.Category)r.names[e.Key] = e.Name}}@@ -814,10 +816,11 @@ func CustomKeyCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID}out := make(map[string]string, len(entries))for _, e := range entries {- if IsBuiltIn(e.Key) || !IsCategory(e.Category) {+ category, ok := ParseCategory(e.Category)+ if IsBuiltIn(e.Key) || !ok {continue}- out[e.Key] = e.Category+ out[e.Key] = category}return out, nil}diff --git a/server/internal/issuestatus/mixed_categories_test.go b/server/internal/issuestatus/mixed_categories_test.gonew file mode 100644index 0000000000..b27ffa32c0--- /dev/null+++ b/server/internal/issuestatus/mixed_categories_test.go@@ -0,0 +1,44 @@+package issuestatus++import (+ "context"+ "testing"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestPreBackfillCategoriesPreserveLifecycleAndWire(t *testing.T) {+ ctx := context.Background()+ for _, old := range Canonical() {+ t.Run(old, func(t *testing.T) {+ category, _ := CategoryForBehavior(old)+ key := "custom_" + old+ // Do not use custom(): that fixture already normalizes its input.+ q := newFakeQuerier(db.IssueStatus{Key: key, Category: old, WorkspaceID: testWorkspace})+ behavior := key+ if old == Done || old == Cancelled {+ behavior = old+ }+ if got := Effective(ctx, q, testWorkspace, key); got != behavior {+ t.Fatalf("Effective = %s, want %s", got, behavior)+ }+ if got := Category(ctx, q, testWorkspace, key); got != category {+ t.Fatalf("Category = %s, want %s", got, category)+ }+ r := NewResolver(testWorkspace)+ if got := r.Effective(ctx, q, key); got != behavior {+ t.Fatalf("resolver Effective = %s", got)+ }+ if got := r.Category(ctx, q, key); got != category {+ t.Fatalf("resolver Category = %s", got)+ }+ keys, err := CustomKeyCategories(ctx, q, testWorkspace)+ if err != nil || keys[key] != category {+ t.Fatalf("custom category map = %v, %v", keys, err)+ }+ if WireCategory(key, old) != WireCategory(key, category) {+ t.Fatal("backfill changes the wire bucket")+ }+ })+ }+}diff --git a/server/internal/service/delegated_failure_mixed_categories_test.go b/server/internal/service/delegated_failure_mixed_categories_test.gonew file mode 100644index 0000000000..0bb8120eb5--- /dev/null+++ b/server/internal/service/delegated_failure_mixed_categories_test.go@@ -0,0 +1,55 @@+package service++import (+ "context"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestPendingRecoveryLegacyTerminalHistoryDoesNotStarveAnotherWorkspace(t *testing.T) {+ ctx := context.Background()+ history, historyService := seedDelegatedFailureFixture(t)+ historyRows := testutil.New(history.pool, history.workspaceID, history.userID)+ historyRows.Insert(t, "issue_status", testutil.Cols{+ "workspace_id": history.workspaceID, "key": "legacy_closed", "name": "Closed", "category": "cancelled", "color": "#123456",+ })+ signal := func(f *delegatedFailureFixture, svc *TaskService) pgtype.UUID {+ t.Helper()+ failed := f.insertWorkerTask(t, "failed", "comment", 1, 2)+ rows := testutil.New(f.pool, f.workspaceID, f.userID)+ rows.Exec(t, `UPDATE agent_task_queue SET failure_reason='agent_error.process_failure', completed_at=now() WHERE id=$1`, failed)+ target, created, err := svc.ensureDelegatedFailureRecoveryComment(ctx, failed)+ if err != nil || !created || target == nil {+ t.Fatalf("create signal: %v, %v", created, err)+ }+ return target.comment.ID+ }+ for range 100 {+ signal(history, historyService)+ }+ historyRows.Exec(t, `UPDATE issue SET status='legacy_closed' WHERE id=$1`, history.issueID)+ live, svc := seedDelegatedFailureFixture(t)+ target := signal(live, svc)+ pending, err := svc.Queries.ListPendingDelegatedFailureRecoveries(ctx, 100)+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, row := range pending {+ if row.ID == target {+ found = true+ }+ }+ if !found {+ t.Fatal("100 old terminal signals starved another workspace's live recovery")+ }+ if len(pending) != 1 {+ t.Fatalf("scan returned %d signals, want only the live signal", len(pending))+ }+ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)+ if err != nil || result.Replayed != 1 {+ t.Fatalf("live recovery = %+v, %v; want one replay", result, err)+ }+}diff --git a/server/internal/service/delegated_failure_recovery_test.go b/server/internal/service/delegated_failure_recovery_test.goindex 55bbedbd0e..a8f99c05e0 100644--- a/server/internal/service/delegated_failure_recovery_test.go+++ b/server/internal/service/delegated_failure_recovery_test.go@@ -338,6 +338,8 @@ func TestPendingDelegatedFailureSweepPrefiltersUnresumableSourceIssues(t *testin{name: "built-in backlog", status: "backlog"},{name: "built-in done", status: "done"},{name: "custom closed-category status", status: "shelved", customCategory: "closed"},+ {name: "pre-backfill cancelled category", status: "legacy_shelved", customCategory: "cancelled"},+ {name: "pre-backfill custom backlog stays live", status: "legacy_later", customCategory: "backlog", wantScanned: true},{name: "source issue still live", status: "in_progress", wantScanned: true},} {t.Run(tc.name, func(t *testing.T) {diff --git a/server/migrations/478_issue_status_category_expand.down.sql b/server/migrations/478_issue_status_category_expand.down.sqlnew file mode 100644index 0000000000..f5e8852c39--- /dev/null+++ b/server/migrations/478_issue_status_category_expand.down.sql@@ -0,0 +1,4 @@+-- Forward-only: restoring either strict vocabulary would reject mixed data.+-- Keep compatibility constraints/functions; repair forward and contract only+-- after the separate backfill and verification have completed (MUL-7365).+SELECT 1;diff --git a/server/migrations/478_issue_status_category_expand.up.sql b/server/migrations/478_issue_status_category_expand.up.sqlnew file mode 100644index 0000000000..fd57bbfa0d--- /dev/null+++ b/server/migrations/478_issue_status_category_expand.up.sql@@ -0,0 +1,46 @@+-- MUL-7365: expand only. Pending 469 is skipped by cmd/migrate; applied 469+-- remains historical fact. No catalog rows (including archived rows) change.+-- The runner sends this file as one implicit transaction. Bound lock acquisition+-- and execution; NOT VALID avoids a table scan while holding the DDL lock.+SET LOCAL lock_timeout = '2s';+SET LOCAL statement_timeout = '10s';++CREATE OR REPLACE FUNCTION issue_status_category(p_category TEXT)+RETURNS TEXT LANGUAGE sql IMMUTABLE PARALLEL SAFE AS $function$+ SELECT CASE p_category+ WHEN 'backlog' THEN 'unstarted' WHEN 'todo' THEN 'unstarted'+ WHEN 'in_progress' THEN 'started' WHEN 'in_review' THEN 'started'+ WHEN 'blocked' THEN 'started' WHEN 'cancelled' THEN 'closed'+ ELSE p_category END+$function$;++ALTER TABLE issue_status+ DROP CONSTRAINT IF EXISTS issue_status_category_check,+ DROP CONSTRAINT IF EXISTS issue_status_system_is_canonical,+ ADD CONSTRAINT issue_status_category_check CHECK (+ category IN ('backlog', 'todo', 'in_progress', 'in_review', 'blocked',+ 'done', 'cancelled', 'unstarted', 'started', 'closed')+ ) NOT VALID,+ ADD CONSTRAINT issue_status_system_is_canonical CHECK (+ NOT is_system OR (key, category) IN (+ ('backlog', 'backlog'), ('backlog', 'unstarted'),+ ('todo', 'todo'), ('todo', 'unstarted'),+ ('in_progress', 'in_progress'), ('in_progress', 'started'),+ ('in_review', 'in_review'), ('in_review', 'started'),+ ('blocked', 'blocked'), ('blocked', 'started'),+ ('done', 'done'), ('cancelled', 'cancelled'), ('cancelled', 'closed')+ )+ ) NOT VALID;++CREATE OR REPLACE FUNCTION issue_effective_status(p_workspace_id UUID, p_status TEXT)+RETURNS TEXT LANGUAGE sql STABLE PARALLEL SAFE AS $function$+ SELECT CASE+ WHEN p_status IN ('backlog', 'todo', 'in_progress', 'in_review', 'done', 'blocked', 'cancelled', 'triage') THEN p_status+ ELSE COALESCE((SELECT CASE s.category+ WHEN 'done' THEN 'done'+ WHEN 'cancelled' THEN 'cancelled'+ WHEN 'closed' THEN 'cancelled'+ ELSE p_status END+ FROM issue_status s WHERE s.workspace_id = p_workspace_id AND s.key = p_status), p_status)+ END+$function$;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex cd2cae8394..825f829f7a 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -5737,7 +5737,8 @@ WHERE recovery.author_type = 'system'-- 'backlog' stopped matching at all. 'backlog' stays a key test: parking is-- built-in behavior a custom unstarted status does not inherit. (MUL-7364)AND source_issue.status NOT IN ('done', 'cancelled', 'backlog')- AND COALESCE(source_status.category, '') NOT IN ('done', 'closed')+ -- Include the old terminal spelling until the independent backfill finishes.+ AND COALESCE(source_status.category, '') NOT IN ('done', 'closed', 'cancelled')AND source_agent.archived_at IS NULLAND source_agent.runtime_id IS NOT NULLAND source_agent.workspace_id = source_issue.workspace_iddiff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.goindex fee3f783ba..7cc6dbe271 100644--- a/server/pkg/db/generated/issue_status.sql.go+++ b/server/pkg/db/generated/issue_status.sql.go@@ -13,6 +13,7 @@ import (const archiveIssueStatusEntry = `-- name: ArchiveIssueStatusEntry :oneUPDATE issue_status SET+ category = issue_status_category(category),archived_at = now(),updated_at = now()WHERE id = $1::uuid@@ -87,7 +88,7 @@ VALUES (COALESCE((SELECT MAX(position) + 1 FROM issue_statusWHERE workspace_id = $1::uuid- AND category = $5::text),+ AND issue_status_category(category) = $5::text),0))@@ -212,7 +213,7 @@ func (q *Queries) GetIssueStatusEntryByKey(ctx context.Context, arg GetIssueStatconst listActiveCustomIssueStatusEntries = `-- name: ListActiveCustomIssueStatusEntries :manySELECT id, workspace_id, key, name, description, category, color, is_system, position, archived_at, created_at, updated_at, icon FROM issue_statusWHERE workspace_id = $1::uuid- AND category = $2::text+ AND issue_status_category(category) = $2::textAND is_system = FALSEAND archived_at IS NULLORDER BY position, key@@ -265,7 +266,7 @@ SELECT id, workspace_id, key, name, description, category, color, is_system, posWHERE workspace_id = $1::uuidAND ($2::bool OR archived_at IS NULL)ORDER BY- CASE category WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,+ CASE issue_status_category(category) WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,position,CASE WHEN is_system THEN 0 ELSE 1 END,CASE key@@ -325,7 +326,7 @@ func (q *Queries) ListIssueStatusEntries(ctx context.Context, arg ListIssueStatuconst listIssueStatusKeysByCategories = `-- name: ListIssueStatusKeysByCategories :manySELECT key FROM issue_statusWHERE workspace_id = $1::uuid- AND category = ANY($2::text[])+ AND issue_status_category(category) = ANY($2::text[])`type ListIssueStatusKeysByCategoriesParams struct {@@ -392,7 +393,8 @@ func (q *Queries) LockIssueStatusCatalogShared(ctx context.Context, workspaceIDconst reorderIssueStatusEntries = `-- name: ReorderIssueStatusEntries :execrowsUPDATE issue_status s-SET position = ($1::float8[])[v.ordinality],+SET category = issue_status_category(s.category),+ position = ($1::float8[])[v.ordinality],updated_at = now()FROM unnest($4::uuid[]) WITH ORDINALITY AS v(id, ordinality)WHERE s.id = v.id@@ -455,6 +457,7 @@ func (q *Queries) SeedIssueStatusEntries(ctx context.Context, workspaceID pgtypeconst updateIssueStatusEntry = `-- name: UpdateIssueStatusEntry :oneUPDATE issue_status SET+ category = issue_status_category(category),name = COALESCE($1, name),description = COALESCE($2, description),color = COALESCE($3, color),diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 2af1f0cafa..eb16e2e1e4 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2133,7 +2133,8 @@ WHERE recovery.author_type = 'system'-- 'backlog' stopped matching at all. 'backlog' stays a key test: parking is-- built-in behavior a custom unstarted status does not inherit. (MUL-7364)AND source_issue.status NOT IN ('done', 'cancelled', 'backlog')- AND COALESCE(source_status.category, '') NOT IN ('done', 'closed')+ -- Include the old terminal spelling until the independent backfill finishes.+ AND COALESCE(source_status.category, '') NOT IN ('done', 'closed', 'cancelled')AND source_agent.archived_at IS NULLAND source_agent.runtime_id IS NOT NULLAND source_agent.workspace_id = source_issue.workspace_iddiff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sqlindex dea2874044..110f6b8ab8 100644--- a/server/pkg/db/queries/issue_status.sql+++ b/server/pkg/db/queries/issue_status.sql@@ -24,7 +24,7 @@ SELECT * FROM issue_statusWHERE workspace_id = sqlc.arg('workspace_id')::uuidAND (sqlc.arg('include_archived')::bool OR archived_at IS NULL)ORDER BY- CASE category WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,+ CASE issue_status_category(category) WHEN 'unstarted' THEN 0 WHEN 'started' THEN 1 WHEN 'done' THEN 2 WHEN 'closed' THEN 3 ELSE 4 END,position,CASE WHEN is_system THEN 0 ELSE 1 END,CASE key@@ -64,7 +64,7 @@ VALUES (COALESCE((SELECT MAX(position) + 1 FROM issue_statusWHERE workspace_id = sqlc.arg('workspace_id')::uuid- AND category = sqlc.arg('category')::text),+ AND issue_status_category(category) = sqlc.arg('category')::text),0))@@ -75,6 +75,7 @@ RETURNING *;-- 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+ category = issue_status_category(category),name = COALESCE(sqlc.narg('name'), name),description = COALESCE(sqlc.narg('description'), description),color = COALESCE(sqlc.narg('color'), color),@@ -95,6 +96,7 @@ RETURNING *;-- it — Effective ignores archived_at, so their behavior is unchanged — while-- Resolve rejects it, so nothing new can be assigned to it.UPDATE issue_status SET+ category = issue_status_category(category),archived_at = now(),updated_at = now()WHERE id = sqlc.arg('id')::uuid@@ -142,7 +144,7 @@ SELECT pg_advisory_xact_lock_shared(hashtextextended(sqlc.arg('workspace_id')::u-- still appear in their category's column.SELECT key FROM issue_statusWHERE workspace_id = sqlc.arg('workspace_id')::uuid- AND category = ANY(sqlc.arg('categories')::text[]);+ AND issue_status_category(category) = ANY(sqlc.arg('categories')::text[]);-- name: ListActiveCustomIssueStatusEntries :many-- One category's ACTIVE custom statuses — the exact set a reorder must cover.@@ -150,7 +152,7 @@ WHERE workspace_id = sqlc.arg('workspace_id')::uuid-- archived concurrently cannot slip in or out between validation and write.SELECT * FROM issue_statusWHERE workspace_id = sqlc.arg('workspace_id')::uuid- AND category = sqlc.arg('category')::text+ AND issue_status_category(category) = sqlc.arg('category')::textAND is_system = FALSEAND archived_at IS NULLORDER BY position, key;@@ -164,7 +166,8 @@ ORDER BY position, key;-- Legacy custom-only callers preserve the positions occupied by custom rows.-- Archived rows remain frozen.UPDATE issue_status s-SET position = (sqlc.arg('positions')::float8[])[v.ordinality],+SET category = issue_status_category(s.category),+ position = (sqlc.arg('positions')::float8[])[v.ordinality],updated_at = now()FROM unnest(sqlc.arg('ids')::uuid[]) WITH ORDINALITY AS v(id, ordinality)WHERE s.id = v.id