Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6243 feat(issue-status): board fetches by category; archive retires without migration (#7084)
Bohan Jiang14c2e4e831e3
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 667f6b8be5..24ad1cebd8 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -3285,8 +3285,9 @@ export class ApiClient {}/**- * Archives a custom status. The server returns 409 while any issue still- * sits on it — move those issues first. Built-in statuses return 403.+ * Archives a custom status, retiring it from future use. Issues already on it+ * keep it and keep behaving as their category prescribes; only new+ * assignments are refused. Built-in statuses return 403.*/async archiveIssueStatus(id: string): Promise<IssueStatusEntry> {const raw = await this.fetch<unknown>(`/api/issue-statuses/${id}`, { method: "DELETE" });diff --git a/packages/core/issue-statuses/hooks.ts b/packages/core/issue-statuses/hooks.tsnew file mode 100644index 0000000000..48281ee0de--- /dev/null+++ b/packages/core/issue-statuses/hooks.ts@@ -0,0 +1,15 @@+import { useQuery } from "@tanstack/react-query";+import { useMemo } from "react";+import { buildIssueStatusCatalog, issueStatusListOptions, type IssueStatusCatalog } from "./queries";++/**+ * The workspace status catalog, resolved and memoized (MUL-6243).+ *+ * Takes `wsId` explicitly rather than reading it from context, per the repo's+ * state rules — the catalog is per-workspace, and switching workspaces does not+ * remount the app, so a module-level snapshot would go stale.+ */+export function useIssueStatuses(wsId: string): IssueStatusCatalog {+ const { data } = useQuery({ ...issueStatusListOptions(wsId), enabled: Boolean(wsId) });+ return useMemo(() => buildIssueStatusCatalog(data), [data]);+}diff --git a/packages/core/issue-statuses/index.ts b/packages/core/issue-statuses/index.tsnew file mode 100644index 0000000000..028dbddd8a--- /dev/null+++ b/packages/core/issue-statuses/index.ts@@ -0,0 +1,8 @@+export {+ issueStatusKeys,+ issueStatusListOptions,+ buildIssueStatusCatalog,+ isIssueStatusCategory,+ type IssueStatusCatalog,+} from "./queries";+export { useIssueStatuses } from "./hooks";diff --git a/packages/core/issue-statuses/queries.test.ts b/packages/core/issue-statuses/queries.test.tsnew file mode 100644index 0000000000..4c0383f60f--- /dev/null+++ b/packages/core/issue-statuses/queries.test.ts@@ -0,0 +1,89 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";+import { buildIssueStatusCatalog, isIssueStatusCategory } from "./queries";+import type { IssueStatusEntry } from "../types";++function entry(key: string, category: string, name = key, archivedAt: string | null = null): IssueStatusEntry {+ return {+ id: key, workspace_id: "ws-1", key, name, description: "",+ category: category as IssueStatusEntry["category"], color: "#123456",+ is_system: false, position: 0, archived_at: archivedAt,+ created_at: "", updated_at: "",+ };+}++describe("buildIssueStatusCatalog", () => {+ // The catalog is fetched async, but a status must render on the very first+ // paint. Built-in keys are their own category, so an unloaded catalog still+ // resolves all 7 — which is what keeps the default workspace identical+ // before the request lands.+ it("resolves every built-in with no catalog loaded", () => {+ const c = buildIssueStatusCatalog(undefined);+ expect(c.isLoaded).toBe(false);+ for (const key of ["backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled"]) {+ expect(c.categoryOf(key)).toBe(key);+ }+ expect(c.labelOf("in_review")).toBe("In Review");+ });++ it("maps a custom status to its category and name", () => {+ const c = buildIssueStatusCatalog([entry("human_review", "in_review", "Human Review")]);+ expect(c.categoryOf("human_review")).toBe("in_review");+ expect(c.labelOf("human_review")).toBe("Human Review");+ expect(c.entryOf("human_review")?.key).toBe("human_review");+ });++ // An issue can carry a status created moments ago in another session. Falling+ // back to a renderable category beats dropping the issue.+ it("falls back for a status the catalog does not know", () => {+ const c = buildIssueStatusCatalog([]);+ expect(c.categoryOf("ghost")).toBe("todo");+ expect(c.labelOf("ghost")).toBe("ghost");+ expect(c.entryOf("ghost")).toBeUndefined();+ });++ it("ignores a corrupt category rather than trusting it", () => {+ const c = buildIssueStatusCatalog([entry("weird", "started")]);+ expect(c.categoryOf("weird")).toBe("todo");+ });++ it("groups by category in catalog order", () => {+ const c = buildIssueStatusCatalog([+ entry("human_review", "in_review"),+ entry("gate_approved", "done"),+ ]);+ expect(c.inCategory("in_review").map((e) => e.key)).toEqual(["human_review"]);+ expect(c.inCategory("backlog")).toEqual([]);+ });++ it("isIssueStatusCategory accepts exactly the 7", () => {+ expect(isIssueStatusCategory("in_review")).toBe(true);+ expect(isIssueStatusCategory("human_review")).toBe(false);+ });+});++// Archiving retires a status from FUTURE assignment but leaves existing issues+// on it. Those issues must keep their real name, colour and category — dropping+// archived rows from resolution would degrade them to a raw key with a guessed+// category, which is exactly what the product decision rules out.+describe("archived statuses stay resolvable", () => {+ const archived = entry("gate_approved", "done", "Gate Approved", "2026-01-01T00:00:00Z");+ const active = entry("human_review", "in_review", "Human Review");+ const c = buildIssueStatusCatalog([active, archived]);++ it("keeps name and category for an issue left on an archived status", () => {+ expect(c.labelOf("gate_approved")).toBe("Gate Approved");+ expect(c.categoryOf("gate_approved")).toBe("done");+ expect(c.entryOf("gate_approved")?.color).toBe("#123456");+ });++ it("excludes archived from the assignable set", () => {+ expect(c.activeStatuses.map((e) => e.key)).toEqual(["human_review"]);+ expect(c.statuses.map((e) => e.key)).toEqual(["human_review", "gate_approved"]);+ });++ it("excludes archived from a category's pickable list", () => {+ expect(c.inCategory("done")).toEqual([]);+ expect(c.inCategory("in_review").map((e) => e.key)).toEqual(["human_review"]);+ });+});diff --git a/packages/core/issue-statuses/queries.ts b/packages/core/issue-statuses/queries.tsnew file mode 100644index 0000000000..a0fba556c5--- /dev/null+++ b/packages/core/issue-statuses/queries.ts@@ -0,0 +1,106 @@+import { queryOptions } from "@tanstack/react-query";+import { api } from "../api";+import { STATUS_CONFIG, STATUS_ORDER } from "../issues/config";+import type { IssueStatusCategory, IssueStatusEntry } from "../types";++/**+ * The workspace issue status catalog (MUL-6243).+ *+ * A workspace always has the 7 built-in statuses and may define custom ones.+ * Every status — built-in or custom — belongs to exactly one of the 7+ * CATEGORIES, and the category is what determines platform behavior, board+ * column and presentation. So this catalog answers one question for the UI:+ * given a status key stored on an issue, what is its label, color and category?+ */++export const issueStatusKeys = {+ all: (wsId: string) => ["issue-statuses", wsId] as const,+ list: (wsId: string) => [...issueStatusKeys.all(wsId), "list"] as const,+};++export function issueStatusListOptions(wsId: string) {+ return queryOptions({+ queryKey: issueStatusKeys.list(wsId),+ // ARCHIVED entries included on purpose. Archiving retires a status from+ // future assignment but leaves existing issues on it, and those issues must+ // keep their real name, color and category. Dropping archived rows here+ // would degrade them to a raw key with a guessed category. Pickers use+ // `activeStatuses`, which excludes them. (MUL-6243)+ queryFn: () => api.listIssueStatuses(true),+ select: (data) => data.statuses,+ // The catalog changes only when an admin edits it, which is rare, so a+ // generous stale time keeps this off the critical path of every render+ // that needs a status label.+ staleTime: 5 * 60_000,+ });+}++/**+ * A resolved view over the catalog. Every lookup falls back to something+ * renderable, because an issue can legitimately carry a status this client has+ * not heard of: a status created moments ago in another session, or one whose+ * catalog fetch has not landed yet.+ */+export interface IssueStatusCatalog {+ /**+ * Every status in display order, ARCHIVED INCLUDED, so an issue left on an+ * archived status still resolves to its real name, color and category.+ * For anything that offers a status to pick, use `activeStatuses`.+ */+ statuses: IssueStatusEntry[];+ /** Assignable statuses — `statuses` minus archived ones. */+ activeStatuses: IssueStatusEntry[];+ /** Category for a status key; falls back to the key when it is a built-in, else "todo". */+ categoryOf: (statusKey: string) => IssueStatusCategory;+ /** Human label for a status key; falls back to the category label, then the raw key. */+ labelOf: (statusKey: string) => string;+ /** Catalog entry for a status key, when the catalog knows it. */+ entryOf: (statusKey: string) => IssueStatusEntry | undefined;+ /** ACTIVE statuses belonging to one category, in display order. */+ inCategory: (category: IssueStatusCategory) => IssueStatusEntry[];+ /** True once the catalog has loaded; false while it is still in flight. */+ isLoaded: boolean;+}++const BUILT_IN = new Set<string>(STATUS_ORDER);++export function isIssueStatusCategory(value: string): value is IssueStatusCategory {+ return BUILT_IN.has(value);+}++/**+ * Builds the resolved catalog from a raw entry list. Pure, so the store and+ * other non-React callers can use it with a list they already hold.+ */+export function buildIssueStatusCatalog(+ entries: IssueStatusEntry[] | undefined,+): IssueStatusCatalog {+ const list = entries ?? [];+ const byKey = new Map(list.map((e) => [e.key, e]));++ const categoryOf = (statusKey: string): IssueStatusCategory => {+ const category = byKey.get(statusKey)?.category;+ if (category && isIssueStatusCategory(category)) return category;+ // A built-in key IS its own category, so an unloaded catalog still resolves+ // all 7 correctly — which is what keeps the default workspace rendering+ // identically before the fetch lands.+ if (isIssueStatusCategory(statusKey)) return statusKey;+ // An unknown custom key: render it somewhere sane rather than dropping it.+ return "todo";+ };++ return {+ statuses: list,+ activeStatuses: list.filter((e) => !e.archived_at),+ categoryOf,+ entryOf: (statusKey) => byKey.get(statusKey),+ labelOf: (statusKey) => {+ const entry = byKey.get(statusKey);+ if (entry) return entry.name;+ if (isIssueStatusCategory(statusKey)) return STATUS_CONFIG[statusKey]?.label ?? statusKey;+ return statusKey;+ },+ inCategory: (category) => list.filter((e) => e.category === category && !e.archived_at),+ isLoaded: entries !== undefined,+ };+}diff --git a/packages/core/issues/cache-coordinator.ts b/packages/core/issues/cache-coordinator.tsindex 1bf4be6d37..6e97300357 100644--- a/packages/core/issues/cache-coordinator.ts+++ b/packages/core/issues/cache-coordinator.ts@@ -1,3 +1,4 @@+import { issueStatusCategory, normalizeStatusPatch } from "./status-category";import {hashKey,type InfiniteData,@@ -18,6 +19,7 @@ import {findIssueLocation,moveBucketTotal,patchIssueInBuckets,+ patchNeedsInvalidation,removeIssueFromBuckets,} from "./cache-helpers";import {@@ -263,7 +265,7 @@ export function applyIssueChange(qc: QueryClient,wsId: string,id: string,- patch: Partial<Issue>,+ rawPatch: Partial<Issue>,opts: {/** Which membership dimensions this change actually moved — compute via* `issueChangedDims` (mutations) or the server's WS flags. */@@ -275,6 +277,10 @@ export function applyIssueChange(},): IssueCacheChangeResult {const { changed, baseIssue } = opts;+ // Normalize ONCE, at the door. Every write below is a `{...entity, ...patch}`+ // spread, and an optimistic `{status}` patch would otherwise leave the stale+ // status_category on the entity while the card moves buckets. (MUL-6243)+ const patch = normalizeStatusPatch(rawPatch);const prevLists: [QueryKey, ListIssuesCache][] = [];const prevFlatLists: [QueryKey, IssueFlatCache][] = [];const prevTableRows: [QueryKey, IssueTableRowCache][] = [];@@ -301,6 +307,11 @@ export function applyIssueChange(if (loc) {if (!prevIssue) prevIssue = loc.issue;+ // A status this client cannot resolve to a category makes+ // patchIssueInBuckets a no-op. The row DID move on the server, so+ // treating that as "nothing to do" would leave the card in its old+ // column forever — force a refetch instead. (MUL-6243)+ if (patchNeedsInvalidation(patch)) staleKeys.push(key);let next: ListIssuesCache;if (filterTouched) {const membership = issueMatchesListFilter(@@ -350,7 +361,22 @@ export function applyIssueChange(// buckets; anything else (e.g. member→member reassignment) leaves// this list's pages and counts untouched.if (!changed.status || patch.status === undefined) continue;- const next = moveBucketTotal(data, baseIssue.status, patch.status);+ // Bucket totals are per category (MUL-6243).+ // patch.status_category is authoritative when the server sent it; the+ // key-only fallback covers built-ins.+ const fromCategory = issueStatusCategory(baseIssue);+ const toCategory = issueStatusCategory({+ status: patch.status,+ status_category: patch.status_category,+ });+ if (!fromCategory || !toCategory) {+ // An unresolvable custom status must NOT be a silent no-op: the row+ // moved on the server, so leaving this cache untouched drifts the+ // off-window totals permanently. Force a refetch instead.+ staleKeys.push(key);+ continue;+ }+ const next = moveBucketTotal(data, fromCategory, toCategory);if (next !== data) {prevLists.push([key, data]);qc.setQueryData<ListIssuesCache>(key, next);@@ -364,7 +390,12 @@ export function applyIssueChange(}if (isMember === false) {// Left the list entirely — the bucket it was counted in loses one.- const next = decrementBucketTotal(data, baseIssue.status);+ const leavingCategory = issueStatusCategory(baseIssue);+ if (!leavingCategory) {+ staleKeys.push(key);+ continue;+ }+ const next = decrementBucketTotal(data, leavingCategory);if (next !== data) {prevLists.push([key, data]);qc.setQueryData<ListIssuesCache>(key, next);diff --git a/packages/core/issues/cache-helpers.test.ts b/packages/core/issues/cache-helpers.test.tsindex c4f23ebf40..ba7513213e 100644--- a/packages/core/issues/cache-helpers.test.ts+++ b/packages/core/issues/cache-helpers.test.ts@@ -1,12 +1,17 @@import { describe, expect, it } from "vitest";-import type { Issue, ListIssuesCache } from "../types";-import { insertByPosition, patchIssueInBuckets } from "./cache-helpers";+import type { Issue, IssueStatusCategory, ListIssuesCache } from "../types";+import { insertByPosition, patchIssueInBuckets, patchNeedsInvalidation } from "./cache-helpers";+import { statusCategoryOfKey, normalizeStatusPatch } from "./status-category";const WS_ID = "ws-1";+// The server now sends status_category on EVERY issue, built-ins included, so+// fixtures must carry it. Without it a patch that leaves a stale category on the+// entity looks correct here while being wrong in production. (MUL-6243)function mk(id: string, status: Issue["status"], position: number): Issue {return {id,+ status_category: statusCategoryOfKey(status),workspace_id: WS_ID,number: 1,identifier: `MUL-${id}`,@@ -36,8 +41,9 @@ function cache(byStatus: ListIssuesCache["byStatus"]): ListIssuesCache {return { byStatus };}-function ids(c: ListIssuesCache, status: Issue["status"]): string[] {- return (c.byStatus[status]?.issues ?? []).map((i) => i.id);+// The cache is bucketed by CATEGORY (MUL-6243), so tests index it with one.+function ids(c: ListIssuesCache, status: IssueStatusCategory): string[] {+ return (c.byStatus[status]?.issues ?? []).map((i: Issue) => i.id);}describe("insertByPosition", () => {@@ -148,3 +154,114 @@ describe("patchIssueInBuckets — unknown issue", () => {expect(patchIssueInBuckets(c0, "ghost", { position: 9 })).toBe(c0);});});++// `Issue.status` is still the closed 7-value union — widening it to `string` is+// the follow-up PR. At runtime the server already sends custom keys, so these+// tests cast to describe the real payloads the cache has to survive.+const key = (k: string) => k as Issue["status"];+const cat = (c: string) => c as IssueStatusCategory;++// A status KEY change WITHIN one category must not be treated as a bucket move.+// The cache is bucketed by category while `patch.status` is a key, so comparing+// them directly sent `in_review` -> a custom `human_review` down the cross-bucket+// path, which deleted from and re-inserted into the same bucket using a+// pre-delete snapshot: the card ended up duplicated and the total one too high.+describe("patchIssueInBuckets — status key changes within a category", () => {+ function inReviewCache(): ListIssuesCache {+ return cache({+ in_review: { issues: [mk("a", "in_review", 100), mk("b", "in_review", 200)], total: 2 },+ });+ }++ it("built-in -> custom in the same category replaces in place", () => {+ const next = patchIssueInBuckets(inReviewCache(), "a", {+ status: key("human_review"),+ status_category: cat("in_review"),+ });+ expect(ids(next, "in_review")).toEqual(["a", "b"]);+ expect(next.byStatus.in_review?.total).toBe(2);+ expect(next.byStatus.in_review?.issues.find((i) => i.id === "a")?.status).toBe("human_review");+ });++ it("custom A -> custom B in the same category replaces in place", () => {+ const start = cache({+ in_review: { issues: [{ ...mk("a", key("human_review"), 100), status_category: cat("in_review") }], total: 1 },+ });+ const next = patchIssueInBuckets(start, "a", {+ status: key("second_review"),+ status_category: cat("in_review"),+ });+ expect(ids(next, "in_review")).toEqual(["a"]);+ expect(next.byStatus.in_review?.total).toBe(1);+ expect(next.byStatus.in_review?.issues[0]?.status).toBe("second_review");+ });++ it("custom cross-category move updates both buckets exactly once", () => {+ const next = patchIssueInBuckets(inReviewCache(), "a", {+ status: key("gate_approved"),+ status_category: cat("done"),+ });+ expect(ids(next, "in_review")).toEqual(["b"]);+ expect(next.byStatus.in_review?.total).toBe(1);+ expect(ids(next, "done")).toEqual(["a"]);+ expect(next.byStatus.done?.total).toBe(1);+ });++ // merged inherits the PREVIOUS issue's status_category, so resolving from it+ // would silently keep the card in its old column after a real move.+ it("ignores the stale category on the existing issue", () => {+ const start = cache({+ in_review: { issues: [{ ...mk("a", key("human_review"), 100), status_category: cat("in_review") }], total: 1 },+ });+ const next = patchIssueInBuckets(start, "a", { status: "done" });+ expect(ids(next, "in_review")).toEqual([]);+ expect(ids(next, "done")).toEqual(["a"]);+ });++ it("no-ops on an unresolvable custom status, and flags it for invalidation", () => {+ const start = inReviewCache();+ const next = patchIssueInBuckets(start, "a", { status: key("mystery_status") });+ expect(next).toBe(start);+ expect(patchNeedsInvalidation({ status: key("mystery_status") })).toBe(true);+ expect(patchNeedsInvalidation({ status: "done" })).toBe(false);+ expect(patchNeedsInvalidation({ title: "no status change" })).toBe(false);+ expect(patchNeedsInvalidation({ status: key("x"), status_category: cat("done") })).toBe(false);+ });+});++// The entity must never disagree with the bucket it sits in. A bare+// `{...issue, ...patch}` kept the previous status_category, and because the+// batch API returns only `{updated: n}` and does not refetch bucketed lists,+// that inconsistency was permanent — the next off-window count then decremented+// the wrong bucket.+describe("patchIssueInBuckets — status_category follows status", () => {+ it("built-in -> built-in rewrites the category on the entity", () => {+ const start = cache({ todo: { issues: [mk("a", "todo", 100)], total: 1 } });+ expect(start.byStatus.todo?.issues[0]?.status_category).toBe("todo");++ const next = patchIssueInBuckets(start, "a", { status: "done" });+ const moved = next.byStatus.done?.issues[0];+ expect(moved?.status).toBe("done");+ expect(moved?.status_category).toBe("done");+ expect(ids(next, "todo")).toEqual([]);+ });++ it("built-in -> custom takes the authoritative category from the patch", () => {+ const start = cache({ todo: { issues: [mk("a", "todo", 100)], total: 1 } });+ const next = patchIssueInBuckets(start, "a", {+ status: key("human_review"),+ status_category: cat("in_review"),+ });+ const moved = next.byStatus.in_review?.issues[0];+ expect(moved?.status).toBe("human_review");+ expect(moved?.status_category).toBe("in_review");+ });++ it("never leaves the previous category on an unresolvable status", () => {+ expect(normalizeStatusPatch({ status: key("mystery") }).status_category).toBeUndefined();+ expect(normalizeStatusPatch({ status: "done" }).status_category).toBe("done");+ // A patch that does not touch status is passed through untouched.+ const untouched = { title: "renamed" };+ expect(normalizeStatusPatch(untouched)).toBe(untouched);+ });+});diff --git a/packages/core/issues/cache-helpers.ts b/packages/core/issues/cache-helpers.tsindex 2c638a83f3..1cc3bac2f6 100644--- a/packages/core/issues/cache-helpers.ts+++ b/packages/core/issues/cache-helpers.ts@@ -1,23 +1,24 @@import type {Issue,- IssueStatus,+ IssueStatusCategory,IssueStatusBucket,ListIssuesCache,} from "../types";-import { PAGINATED_STATUSES } from "./queries";+import { PAGINATED_CATEGORIES } from "./queries";+import { issueStatusCategory, normalizeStatusPatch } from "./status-category";const EMPTY_BUCKET: IssueStatusBucket = { issues: [], total: 0 };export function getBucket(resp: ListIssuesCache,- status: IssueStatus,+ status: IssueStatusCategory,): IssueStatusBucket {return resp.byStatus[status] ?? EMPTY_BUCKET;}export function setBucket(resp: ListIssuesCache,- status: IssueStatus,+ status: IssueStatusCategory,bucket: IssueStatusBucket,): ListIssuesCache {return { ...resp, byStatus: { ...resp.byStatus, [status]: bucket } };@@ -27,10 +28,10 @@ export function setBucket(export function findIssueLocation(resp: ListIssuesCache,id: string,-): { status: IssueStatus; issue: Issue } | null {- for (const status of PAGINATED_STATUSES) {+): { status: IssueStatusCategory; issue: Issue } | null {+ for (const status of PAGINATED_CATEGORIES) {const bucket = resp.byStatus[status];- const found = bucket?.issues.find((i) => i.id === id);+ const found = bucket?.issues.find((i: Issue) => i.id === id);if (found) return { status, issue: found };}return null;@@ -41,9 +42,15 @@ export function addIssueToBuckets(resp: ListIssuesCache,issue: Issue,): ListIssuesCache {- const bucket = getBucket(resp, issue.status);- if (bucket.issues.some((i) => i.id === issue.id)) return resp;- return setBucket(resp, issue.status, {+ // An unresolvable custom status has no column to place the issue in. The+ // caller is responsible for invalidating instead — silently dropping it would+ // leave the board missing a row that exists on the server. Callers use+ // `issueStatusCategory(issue) === null` to detect this before calling.+ const category = issueStatusCategory(issue);+ if (!category) return resp;+ const bucket = getBucket(resp, category);+ if (bucket.issues.some((i: Issue) => i.id === issue.id)) return resp;+ return setBucket(resp, category, {issues: [...bucket.issues, issue],total: bucket.total + 1,});@@ -71,8 +78,8 @@ export function removeIssueFromBuckets(*/export function moveBucketTotal(resp: ListIssuesCache,- from: IssueStatus,- to: IssueStatus,+ from: IssueStatusCategory,+ to: IssueStatusCategory,): ListIssuesCache {if (from === to) return resp;const fromBucket = getBucket(resp, from);@@ -91,7 +98,7 @@ export function moveBucketTotal(*/export function decrementBucketTotal(resp: ListIssuesCache,- status: IssueStatus,+ status: IssueStatusCategory,): ListIssuesCache {const bucket = getBucket(resp, status);return setBucket(resp, status, {@@ -126,44 +133,79 @@ export function insertByPosition(issues: Issue[], issue: Issue): Issue[] {export function patchIssueInBuckets(resp: ListIssuesCache,id: string,- patch: Partial<Issue>,+ rawPatch: Partial<Issue>,): ListIssuesCache {const loc = findIssueLocation(resp, id);if (!loc) return resp;+ // Normalized so the merged entity's status_category matches the bucket it+ // lands in; a bare spread would keep the previous category. (MUL-6243)+ const patch = normalizeStatusPatch(rawPatch);const merged: Issue = { ...loc.issue, ...patch };- const nextStatus = patch.status ?? loc.status;- if (nextStatus === loc.status) {+ // Resolve the DESTINATION category before comparing anything. `loc.status` is+ // a CATEGORY (the bucket key) while `patch.status` is a status KEY, so+ // comparing them directly treats a same-category key change — `in_review` to+ // a custom `human_review` — as a cross-bucket move. That path then deletes+ // from and inserts into the same bucket using a pre-delete snapshot, leaving+ // the card duplicated and the total one too high.+ //+ // Resolved from `patch` alone, never from `merged`: merged inherits the+ // PREVIOUS issue's status_category, which would silently keep the old column+ // after a real move.+ const nextCategory =+ patch.status === undefined+ ? loc.status+ : issueStatusCategory({ status: patch.status, status_category: patch.status_category });++ // Unresolvable custom status: no bucket to move it to. Leave the cache alone+ // and let the caller invalidate — see patchNeedsInvalidation.+ if (!nextCategory) return resp;++ if (nextCategory === loc.status) {const bucket = getBucket(resp, loc.status);const positionChanged =patch.position !== undefined && patch.position !== loc.issue.position;if (!positionChanged) {- // Plain field update (labels, metadata, title, …): keep the slot so a- // remote edit never reorders an otherwise-untouched column.+ // Plain field update (labels, metadata, title, a same-category status+ // key change …): keep the slot so a remote edit never reorders an+ // otherwise-untouched column, and never change the total.return setBucket(resp, loc.status, {...bucket,- issues: bucket.issues.map((i) => (i.id === id ? merged : i)),+ issues: bucket.issues.map((i: Issue) => (i.id === id ? merged : i)),});}// Same-column reorder: lift the card out and re-insert at its new slot.return setBucket(resp, loc.status, {...bucket,issues: insertByPosition(- bucket.issues.filter((i) => i.id !== id),+ bucket.issues.filter((i: Issue) => i.id !== id),merged,),});}const fromBucket = getBucket(resp, loc.status);- const toBucket = getBucket(resp, nextStatus);+ const toBucket = getBucket(resp, nextCategory);let next = setBucket(resp, loc.status, {- issues: fromBucket.issues.filter((i) => i.id !== id),+ issues: fromBucket.issues.filter((i: Issue) => i.id !== id),total: Math.max(0, fromBucket.total - 1),});- next = setBucket(next, nextStatus, {+ next = setBucket(next, nextCategory, {issues: insertByPosition(toBucket.issues, merged),total: toBucket.total + 1,});return next;}++/**+ * True when a status patch names a status this client cannot resolve to a+ * category, so `patchIssueInBuckets` will no-op. Callers must invalidate rather+ * than treat that as "nothing to do" — the row moved on the server, and leaving+ * the cache untouched drifts the column and its total permanently.+ */+export function patchNeedsInvalidation(patch: Partial<Issue>): boolean {+ if (patch.status === undefined) return false;+ return (+ issueStatusCategory({ status: patch.status, status_category: patch.status_category }) === null+ );+}diff --git a/packages/core/issues/config/status.ts b/packages/core/issues/config/status.tsindex 185b7980b2..40addeee7c 100644--- a/packages/core/issues/config/status.ts+++ b/packages/core/issues/config/status.ts@@ -1,6 +1,13 @@-import type { IssueStatus } from "../../types";+import type { IssueStatusCategory } from "../../types";-export const STATUS_ORDER: IssueStatus[] = [+// These three are keyed on CATEGORY, not on status key. A workspace can define+// any number of custom statuses, but every one of them belongs to exactly one+// of the 7 categories below — so board columns, the presentation config and the+// paginated fetch all keep a fixed shape. Resolve a status KEY to its category+// with the workspace catalog (`useIssueStatuses`) before indexing these.+// (MUL-6243)++export const STATUS_ORDER: IssueStatusCategory[] = ["backlog","todo","in_progress",@@ -10,7 +17,7 @@ export const STATUS_ORDER: IssueStatus[] = ["cancelled",];-export const ALL_STATUSES: IssueStatus[] = [+export const ALL_STATUSES: IssueStatusCategory[] = ["backlog","todo","in_progress",@@ -21,7 +28,7 @@ export const ALL_STATUSES: IssueStatus[] = [];export const STATUS_CONFIG: Record<- IssueStatus,+ IssueStatusCategory,{label: string;iconColor: string;diff --git a/packages/core/issues/index.ts b/packages/core/issues/index.tsindex f8048761fc..28b892e095 100644--- a/packages/core/issues/index.ts+++ b/packages/core/issues/index.ts@@ -5,3 +5,5 @@ export * from "./mutations";export * from "./ws-updaters";export * from "./config";export * from "./stores";++export { issueStatusCategory, statusCategoryOfKey, normalizeStatusPatch } from "./status-category";diff --git a/packages/core/issues/mutations.ts b/packages/core/issues/mutations.tsindex cfaeccc12d..84eda60ba5 100644--- a/packages/core/issues/mutations.ts+++ b/packages/core/issues/mutations.ts@@ -1,3 +1,4 @@+import { normalizeStatusPatch } from "./status-category";import { hashKey, useMutation, useQueryClient, type QueryKey } from "@tanstack/react-query";import { api } from "../api";import { issueKeys } from "./queries";@@ -184,7 +185,7 @@ export function useUpdateIssue() {(old) =>detachedFromParent? old?.filter((c) => c.id !== id)- : old?.map((c) => (c.id === id ? { ...c, ...patch } : c)),+ : old?.map((c) => (c.id === id ? { ...c, ...normalizeStatusPatch(patch) } : c)),);}return { change, prevChildren, parentId, id };@@ -467,7 +468,7 @@ export function useBatchUpdateIssues() {affectedParentIds.add(parentId);prevChildren.set(parentId, data);qc.setQueryData<Issue[]>(issueKeys.children(wsId, parentId), (old) =>- old?.map((c) => (idSet.has(c.id) ? { ...c, ...patch } : c)),+ old?.map((c) => (idSet.has(c.id) ? { ...c, ...normalizeStatusPatch(patch) } : c)),);}diff --git a/packages/core/issues/queries.ts b/packages/core/issues/queries.tsindex 450e7624ba..f64a2dd339 100644--- a/packages/core/issues/queries.ts+++ b/packages/core/issues/queries.ts@@ -8,7 +8,7 @@ import { api, ApiError } from "../api";import type {Issue,IssueAssigneeType,- IssueStatus,+ IssueStatusCategory,IssueTableFacetsRequest,IssueTableGroupSpec,IssueTableGroupsRequest,@@ -217,18 +217,24 @@ export type AssigneeGroupedIssuesFilter = Omit<export const ISSUE_PAGE_SIZE = 50;/**- * Statuses fetched and paginated into the list/board cache — every lifecycle- * status, `cancelled` included. `cancelled` is a first-class default status- * (MUL-4290), so it lives in the cache and renders like any other column;- * there is no separate "visible board" subset. This constant governs- * fetch/cache membership.+ * CATEGORIES fetched and paginated into the list/board cache — all 7,+ * `cancelled` included. `cancelled` is a first-class default (MUL-4290), so it+ * lives in the cache and renders like any other column; there is no separate+ * "visible board" subset. This constant governs fetch/cache membership.+ *+ * Keyed on category, not on status key (MUL-6243). A workspace can define any+ * number of custom statuses, and bucketing by status would mean one more+ * parallel `listIssues` request on every board load per status added. Bucketing+ * by category keeps the fan-out fixed at 7 forever; a custom status appears in+ * the column of the category it inherits, and the card's own badge is what+ * shows which specific status it is on.*/-export const PAGINATED_STATUSES: readonly IssueStatus[] = ALL_STATUSES;+export const PAGINATED_CATEGORIES: readonly IssueStatusCategory[] = ALL_STATUSES;/** Flatten a bucketed response to a single Issue[] for consumers that want the whole list. */export function flattenIssueBuckets(data: ListIssuesCache) {const out = [];- for (const status of PAGINATED_STATUSES) {+ for (const status of PAGINATED_CATEGORIES) {const bucket = data.byStatus[status];if (bucket) out.push(...bucket.issues);}@@ -237,12 +243,12 @@ export function flattenIssueBuckets(data: ListIssuesCache) {async function fetchFirstPages(filter: MyIssuesFilter = {}, sort?: IssueSortParam): Promise<ListIssuesCache> {const responses = await Promise.all(- PAGINATED_STATUSES.map((status) =>- api.listIssues({ status, limit: ISSUE_PAGE_SIZE, offset: 0, ...sort, ...filter }),+ PAGINATED_CATEGORIES.map((category) =>+ api.listIssues({ status_category: category, limit: ISSUE_PAGE_SIZE, offset: 0, ...sort, ...filter }),),);const byStatus: ListIssuesCache["byStatus"] = {};- PAGINATED_STATUSES.forEach((status, i) => {+ PAGINATED_CATEGORIES.forEach((status: IssueStatusCategory, i: number) => {const res = responses[i]!;byStatus[status] = { issues: res.issues, total: res.total };});diff --git a/packages/core/issues/status-category.ts b/packages/core/issues/status-category.tsnew file mode 100644index 0000000000..d65601ed87--- /dev/null+++ b/packages/core/issues/status-category.ts@@ -0,0 +1,64 @@+import type { Issue, IssueStatusCategory } from "../types";+import { isIssueStatusCategory } from "../issue-statuses";++/**+ * The category an issue's status belongs to — the bucket it occupies on the+ * board (MUL-6243).+ *+ * Pure on purpose: the cache helpers that call it run outside React and must+ * not reach for a catalog. It reads the server-provided `status_category` when+ * present and otherwise falls back to the rule that makes that field optional+ * in the first place — a BUILT-IN status key is its own category. Since custom+ * statuses only exist once an admin creates one, the fallback is exact for+ * every workspace that has none.+ *+ * Returns null when the status is a custom key this response did not resolve,+ * so callers can skip bucketing rather than guessing a wrong column.+ */+export function issueStatusCategory(issue: Pick<Issue, "status" | "status_category">): IssueStatusCategory | null {+ const fromServer = issue.status_category;+ if (fromServer && isIssueStatusCategory(fromServer)) return fromServer;+ if (isIssueStatusCategory(issue.status)) return issue.status;+ return null;+}++/**+ * Category for a bare status KEY, for render paths that hold only the string.+ *+ * Exact for the 7 built-ins, which is every status that exists until an admin+ * defines a custom one. A custom key returns `todo` so presentation lookups+ * always resolve to something renderable; surfaces that must show the real+ * status use the catalog (`useIssueStatuses`) instead. (MUL-6243)+ */+export function statusCategoryOfKey(statusKey: string): IssueStatusCategory {+ return isIssueStatusCategory(statusKey) ? statusKey : "todo";+}++/**+ * Rewrites a patch's `status_category` to match its `status`, before the patch+ * reaches any cache (MUL-6243).+ *+ * The server now sends a category on every issue, so a cached entity looks like+ * `{status: "todo", status_category: "todo"}`. An optimistic patch carries only+ * `{status: "done"}`, and a bare `{...issue, ...patch}` therefore keeps the+ * STALE `status_category: "todo"` while the card moves to the done bucket. A+ * single update self-heals when the full server response lands, but the batch+ * API returns only `{updated: n}` and does not refetch bucketed lists — so+ * without this the entity stays permanently inconsistent with the bucket it+ * sits in, and the next off-window count decrements the wrong bucket.+ *+ * A patch that does not touch `status` is returned unchanged. A custom key with+ * no authoritative category is left alone too: it is unresolvable, and+ * `patchNeedsInvalidation` routes it to a refetch rather than a guess — but the+ * stale inherited value is dropped so nothing downstream trusts it.+ */+export function normalizeStatusPatch(patch: Partial<Issue>): Partial<Issue> {+ if (patch.status === undefined) return patch;+ const category = issueStatusCategory({+ status: patch.status,+ status_category: patch.status_category,+ });+ // Undefined rather than the inherited value: an unresolvable status must not+ // silently keep the previous category.+ return { ...patch, status_category: category ?? undefined };+}diff --git a/packages/core/issues/ws-updaters.ts b/packages/core/issues/ws-updaters.tsindex 134f4aadca..be010370c6 100644--- a/packages/core/issues/ws-updaters.ts+++ b/packages/core/issues/ws-updaters.ts@@ -1,3 +1,4 @@+import { issueStatusCategory } from "./status-category";import type { QueryClient } from "@tanstack/react-query";import { issueKeys } from "./queries";import { labelKeys } from "../labels/queries";@@ -117,8 +118,18 @@ export function onIssueCreated(wsId: string,issue: Issue,) {+ // A custom status this client cannot resolve to a category has no bucket to+ // go in. Inserting nowhere would silently hide an issue that exists on the+ // server, so invalidate the list instead and let the refetch place it.+ // (MUL-6243)+ const bucketable = issueStatusCategory(issue) !== null;for (const [key, data] of qc.getQueriesData<ListIssuesCache>({ queryKey: issueKeys.list(wsId) })) {- if (data) qc.setQueryData<ListIssuesCache>(key, addIssueToBuckets(data, issue));+ if (!data) continue;+ if (bucketable) {+ qc.setQueryData<ListIssuesCache>(key, addIssueToBuckets(data, issue));+ } else {+ qc.invalidateQueries({ queryKey: key });+ }}qc.invalidateQueries({ queryKey: issueKeys.myAll(wsId) });qc.invalidateQueries({ queryKey: issueKeys.flatAll(wsId) });diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 2b3aa04c40..d2ef26319c 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -1,4 +1,4 @@-import type { Issue, IssueMetadata, IssueStatus, IssuePriority, IssueAssigneeType } from "./issue";+import type { Issue, IssueMetadata, IssueStatus, IssueStatusCategory, IssuePriority, IssueAssigneeType } from "./issue";import type { MemberRole } from "./workspace";import type { Project } from "./project";@@ -106,6 +106,15 @@ export interface ListIssuesParams {status?: IssueStatus;/** Multi-value table facet. OR within the field. */statuses?: IssueStatus[];+ /**+ * Filter by status CATEGORY rather than by exact key, so one bucket holds a+ * category's canonical status plus every custom status that inherits it.+ * This is what keeps the board's fan-out fixed at 7 requests however many+ * custom statuses a workspace defines. (MUL-6243)+ */+ status_category?: IssueStatusCategory;+ /** Multi-value form of `status_category`. OR within the field. */+ status_categories?: IssueStatusCategory[];priority?: IssuePriority;/** Multi-value table facet. OR within the field. */priorities?: IssuePriority[];@@ -451,7 +460,8 @@ export interface IssueStatusBucket {* `api.listIssues` responses by the query functions in `issues/queries.ts`.*/export interface ListIssuesCache {- byStatus: Partial<Record<IssueStatus, IssueStatusBucket>>;+ /** Bucketed by status CATEGORY — see PAGINATED_CATEGORIES. (MUL-6243) */+ byStatus: Partial<Record<IssueStatusCategory, IssueStatusBucket>>;}export interface SearchIssueResult extends Issue {diff --git a/packages/core/types/issue-status.ts b/packages/core/types/issue-status.tsindex 45ef496458..36dd7ba0ae 100644--- a/packages/core/types/issue-status.ts+++ b/packages/core/types/issue-status.ts@@ -1,4 +1,4 @@-import type { IssueStatus } from "./issue";+import type { IssueStatusCategory } from "./issue";/*** A workspace's issue status catalog (MUL-6243).@@ -13,8 +13,11 @@ import type { IssueStatus } from "./issue";* behavior.*/-/** A status category, identical to the set of built-in status keys. */-export type IssueStatusCategory = IssueStatus;+// IssueStatusCategory is defined in ./issue, next to IssueStatus, because the+// two only make sense read together: a category is one of the 7 built-in keys,+// and a status key is a category or a workspace's custom key. Re-exported here+// so catalog consumers can import both from one place. (MUL-6243)+export type { IssueStatusCategory } from "./issue";export interface IssueStatusEntry {id: string;diff --git a/packages/core/types/issue.ts b/packages/core/types/issue.tsindex e5b64c0fb2..289ae1786b 100644--- a/packages/core/types/issue.ts+++ b/packages/core/types/issue.ts@@ -1,7 +1,15 @@import type { Label } from "./label";import type { IssuePropertyValues } from "./property";-export type IssueStatus =+/**+ * A status CATEGORY — the behavior equivalence class an issue's status belongs+ * to. There are exactly 7, and each is also the key of the built-in status that+ * defines it, which is why this stayed a closed union while `Issue.status`+ * became open. Board columns, filters and the presentation config are all keyed+ * off categories, so their shape is fixed no matter how many custom statuses a+ * workspace defines. (MUL-6243)+ */+export type IssueStatusCategory =| "backlog"| "todo"| "in_progress"@@ -10,6 +18,18 @@ export type IssueStatus =| "blocked"| "cancelled";+/**+ * A status KEY as stored on the issue.+ *+ * STILL the closed 7-value union. Widening it to `string` — so a workspace's+ * CUSTOM statuses are representable — is the first task of the follow-up PR,+ * because it forces every `Record<IssueStatus, …>` presentation lookup in+ * `packages/views` to resolve a key to its category first. The catalog module+ * and the category type below exist so that change is mechanical rather than+ * exploratory. (MUL-6243)+ */+export type IssueStatus = IssueStatusCategory;+export type IssuePriority = "urgent" | "high" | "medium" | "low" | "none";export type IssueAssigneeType = "member" | "agent" | "squad";@@ -41,6 +61,13 @@ export interface Issue {title: string;description: string | null;status: IssueStatus;+ /**+ * The category `status` belongs to, when the endpoint resolved it. Optional+ * because a BUILT-IN status is its own category and needs no resolution —+ * use `issueStatusCategory(issue)` rather than reading this directly.+ * (MUL-6243)+ */+ status_category?: IssueStatusCategory;priority: IssuePriority;assignee_type: IssueAssigneeType | null;assignee_id: string | null;diff --git a/packages/views/editor/extensions/mention-suggestion.test.tsx b/packages/views/editor/extensions/mention-suggestion.test.tsxindex 94652aa506..de0a701930 100644--- a/packages/views/editor/extensions/mention-suggestion.test.tsx+++ b/packages/views/editor/extensions/mention-suggestion.test.tsx@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen, waitFor } from "@testing-library/react"import { createRef, type ReactNode } from "react";import { describe, it, expect, vi, beforeEach } from "vitest";import { workspaceKeys } from "@multica/core/workspace/queries";-import { issueKeys, PAGINATED_STATUSES } from "@multica/core/issues/queries";+import { issueKeys, PAGINATED_CATEGORIES } from "@multica/core/issues/queries";import { I18nProvider } from "@multica/core/i18n/react";import type { IssueStatus, ListIssuesCache } from "@multica/core/types";import type { QueryClient } from "@tanstack/react-query";@@ -115,7 +115,7 @@ function fakeQc(data: {map.set(JSON.stringify(workspaceKeys.agents("ws-1")), agentsWithPermissions);map.set(JSON.stringify(workspaceKeys.squads("ws-1")), data.squads ?? []);const byStatus: ListIssuesCache["byStatus"] = {};- for (const status of PAGINATED_STATUSES) {+ for (const status of PAGINATED_CATEGORIES) {const bucket = (data.issues ?? []).filter((i) => i.status === status);byStatus[status as IssueStatus] = { issues: bucket as never, total: bucket.length };}diff --git a/packages/views/inbox/components/inbox-detail-label.tsx b/packages/views/inbox/components/inbox-detail-label.tsxindex 982731287d..2e7a39b105 100644--- a/packages/views/inbox/components/inbox-detail-label.tsx+++ b/packages/views/inbox/components/inbox-detail-label.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import { STATUS_CONFIG, PRIORITY_CONFIG } from "@multica/core/issues/config";import { formatDateOnly } from "@multica/core/issues/date";import { useActorName } from "@multica/core/workspace/hooks";@@ -51,7 +52,7 @@ export function InboxDetailLabel({ item }: { item: InboxItem }) {switch (item.type) {case "status_changed": {if (!details.to) return <span>{typeLabels[item.type]}</span>;- const label = STATUS_CONFIG[details.to as IssueStatus]?.label ?? details.to;+ const label = STATUS_CONFIG[statusCategoryOfKey(details.to)]?.label ?? details.to;return (<span className="inline-flex items-center gap-1">{t(($) => $.labels.set_status_to)}diff --git a/packages/views/issues/components/board-column.tsx b/packages/views/issues/components/board-column.tsxindex 6c9f99a245..4c1c651e58 100644--- a/packages/views/issues/components/board-column.tsx+++ b/packages/views/issues/components/board-column.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import { memo, useCallback, useMemo, useState, type ReactNode } from "react";import { Virtuoso } from "react-virtuoso";import { EyeOff, MoreHorizontal, Plus, UserMinus } from "lucide-react";@@ -111,7 +112,7 @@ export const BoardColumn = memo(function BoardColumn({sortLabel?: string | null;}) {const status = group.status;- const cfg = status ? STATUS_CONFIG[status] : null;+ const cfg = status ? STATUS_CONFIG[statusCategoryOfKey(status)] : null;const { setNodeRef, isOver } = useDroppable({ id: group.id });const viewStoreApi = useViewStoreApi();// A status fixed by the open saved view cannot be hidden from the board —diff --git a/packages/views/issues/components/filter-chips-bar.tsx b/packages/views/issues/components/filter-chips-bar.tsxindex bb95a34f53..6ebf02a3f2 100644--- a/packages/views/issues/components/filter-chips-bar.tsx+++ b/packages/views/issues/components/filter-chips-bar.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import { useMemo, type ReactNode } from "react";import {CalendarDays,@@ -349,7 +350,7 @@ function useFilterChips(),value:onlyStatus !== undefined && deltaStatus.length === 1- ? t(($) => $.status[onlyStatus])+ ? t(($) => $.status[statusCategoryOfKey(onlyStatus)]): t(($) => $.filters.chip_status_count, { count: deltaStatus.length }),onRemove: () => clearDimension("status"),});diff --git a/packages/views/issues/components/hidden-columns-panel.tsx b/packages/views/issues/components/hidden-columns-panel.tsxindex 5b28b19547..6a9b0f4bec 100644--- a/packages/views/issues/components/hidden-columns-panel.tsx+++ b/packages/views/issues/components/hidden-columns-panel.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import { Eye, MoreHorizontal } from "lucide-react";import type { IssueStatus } from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";@@ -62,7 +63,7 @@ export function HiddenColumnRow({<div className="flex items-center justify-between rounded-lg px-2.5 py-2 hover:bg-muted/50"><div className="flex items-center gap-2"><StatusIcon status={status} className="h-3.5 w-3.5" />- <span className="text-body">{t(($) => $.status[status])}</span>+ <span className="text-body">{t(($) => $.status[statusCategoryOfKey(status)])}</span></div><div className="flex items-center gap-1.5">{total !== undefined && (diff --git a/packages/views/issues/components/issue-hover-card.tsx b/packages/views/issues/components/issue-hover-card.tsxindex 054008332e..43734f1dd5 100644--- a/packages/views/issues/components/issue-hover-card.tsx+++ b/packages/views/issues/components/issue-hover-card.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import type { ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import { childIssueProgressOptions, issueDetailOptions } from "@multica/core/issues/queries";@@ -180,7 +181,7 @@ function IssueHoverCardBody({)}<spanrole="img"- aria-label={t(($) => $.status[issue.status])}+ aria-label={t(($) => $.status[statusCategoryOfKey(issue.status)])}className="flex shrink-0"><StatusIcon status={issue.status} className="h-3.5 w-3.5 shrink-0" />diff --git a/packages/views/issues/components/pickers/status-picker.tsx b/packages/views/issues/components/pickers/status-picker.tsxindex 64657c0185..9d4ec1ab9d 100644--- a/packages/views/issues/components/pickers/status-picker.tsx+++ b/packages/views/issues/components/pickers/status-picker.tsx@@ -1,5 +1,6 @@"use client";+import { statusCategoryOfKey } from "@multica/core/issues";import { useState } from "react";import type { IssueStatus, UpdateIssueRequest } from "@multica/core/types";import { ALL_STATUSES, STATUS_CONFIG } from "@multica/core/issues/config";@@ -47,7 +48,7 @@ export function StatusPicker({(status != null ? (<><StatusIcon status={status} className="h-3.5 w-3.5 shrink-0" />- <span className="truncate">{t(($) => $.status[status])}</span>+ <span className="truncate">{t(($) => $.status[statusCategoryOfKey(status)])}</span></>) : null)}@@ -65,7 +66,7 @@ export function StatusPicker({}}><StatusIcon status={s} className="h-3.5 w-3.5" />- <span>{t(($) => $.status[s])}</span>+ <span>{t(($) => $.status[statusCategoryOfKey(s)])}</span></PickerItem>);})}diff --git a/packages/views/issues/components/status-heading.tsx b/packages/views/issues/components/status-heading.tsxindex 77273c3170..cc2939e854 100644--- a/packages/views/issues/components/status-heading.tsx+++ b/packages/views/issues/components/status-heading.tsx@@ -1,3 +1,4 @@+import { statusCategoryOfKey } from "@multica/core/issues";import type { IssueStatus } from "@multica/core/types";import { StatusIcon } from "./status-icon";import { useT } from "../../i18n";@@ -14,7 +15,7 @@ export function StatusHeading({<div className="flex items-center gap-2"><span className="inline-flex items-center gap-1.5 text-caption font-semibold"><StatusIcon status={status} className="h-3 w-3" />- {t(($) => $.status[status])}+ {t(($) => $.status[statusCategoryOfKey(status)])}</span><span className="text-caption text-muted-foreground">{count}</span></div>diff --git a/packages/views/issues/components/status-icon.tsx b/packages/views/issues/components/status-icon.tsxindex 81d6b8032c..e18e3108c2 100644--- a/packages/views/issues/components/status-icon.tsx+++ b/packages/views/issues/components/status-icon.tsx@@ -1,3 +1,4 @@+import { statusCategoryOfKey } from "@multica/core/issues";import type { IssueStatus } from "@multica/core/types";import { STATUS_CONFIG } from "@multica/core/issues/config";@@ -167,7 +168,7 @@ export function StatusIcon({inheritColor?: boolean;}) {const knownStatus = status in STATUS_RENDERERS ? (status as IssueStatus) : null;- const cfg = knownStatus ? STATUS_CONFIG[knownStatus] : null;+ const cfg = knownStatus ? STATUS_CONFIG[statusCategoryOfKey(knownStatus)] : null;const Renderer = knownStatus ? STATUS_RENDERERS[knownStatus] : TodoIcon;return (diff --git a/server/internal/handler/actor_guards_test.go b/server/internal/handler/actor_guards_test.goindex 30ad13b791..5ce6d2578e 100644--- a/server/internal/handler/actor_guards_test.go+++ b/server/internal/handler/actor_guards_test.go@@ -133,7 +133,6 @@ func TestRequireHumanActor_IgnoresUnknownActorSource(t *testing.T) {}}-// TestRequireHumanActor_AppliedViaChiRouterUse pins the wiring side of// the contract: when the guard is attached to a chi route group via// r.Use, every endpoint in that group is protected, and a task-tokendiff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.goindex 8aa631c769..3fcec4d036 100644--- a/server/internal/handler/agent_access_test.go+++ b/server/internal/handler/agent_access_test.go@@ -587,7 +587,7 @@ func TestShouldEnqueueOnComment_PrivateAgentGate(t *testing.T) {for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {- got := testHandler.shouldEnqueueAssigneeFallback(ctx, issue, tc.actorType, tc.actorID, commentTriggerComputeOptions{})+ got := testHandler.shouldEnqueueAssigneeFallback(ctx, issue, tc.actorType, tc.actorID, commentTriggerComputeOptions{})if got != tc.want {t.Fatalf("%s\n actor=%s/%s got=%v want=%v",tc.reason, tc.actorType, tc.actorID, got, tc.want)diff --git a/server/internal/handler/agent_permission.go b/server/internal/handler/agent_permission.goindex 7463709201..f2fb732a0b 100644--- a/server/internal/handler/agent_permission.go+++ b/server/internal/handler/agent_permission.go@@ -91,8 +91,8 @@ func (p resolvedPermission) legacyVisibility() string {// - permissionMode == nil && visibility == nil -> caller default (returns ok=false, nil)// - permissionMode provided -> authoritative// - only legacy visibility provided -> mapped:-// "private" -> private-// "workspace" -> public_to + workspace target+// "private" -> private+// "workspace" -> public_to + workspace target//// workspaceID seeds workspace targets (stored as the workspace id). The// returned error is a client-facing 400 message.diff --git a/server/internal/handler/autopilot_webhook_iprl_test.go b/server/internal/handler/autopilot_webhook_iprl_test.goindex dc5f25edb0..6c94d0f985 100644--- a/server/internal/handler/autopilot_webhook_iprl_test.go+++ b/server/internal/handler/autopilot_webhook_iprl_test.go@@ -125,8 +125,8 @@ func TestRemoteAddrHost(t *testing.T) {{"203.0.113.5:1234", "203.0.113.5"},{"[::1]:8080", "::1"},{"[2001:db8::1]:443", "2001:db8::1"},- {"203.0.113.5", "203.0.113.5"}, // bare, no port- {"2001:db8::1", "2001:db8::1"}, // bare IPv6+ {"203.0.113.5", "203.0.113.5"}, // bare, no port+ {"2001:db8::1", "2001:db8::1"}, // bare IPv6{"", ""},}for _, tc := range cases {diff --git a/server/internal/handler/autopilot_webhook_test.go b/server/internal/handler/autopilot_webhook_test.goindex 308400c3f6..9c2c94e2f0 100644--- a/server/internal/handler/autopilot_webhook_test.go+++ b/server/internal/handler/autopilot_webhook_test.go@@ -334,10 +334,10 @@ func TestWebhookEventAllowedByTriggerScope_MultipleFilters(t *testing.T) {func TestSplitWebhookEvent(t *testing.T) {tests := []struct {- input string- wantProvider string- wantName string- wantAction string+ input string+ wantProvider string+ wantName string+ wantAction string}{{"github.workflow_run.completed", "github", "workflow_run", "completed"},{"github.push", "github", "push", ""},diff --git a/server/internal/handler/comment_duplicate_enqueue_race_test.go b/server/internal/handler/comment_duplicate_enqueue_race_test.goindex bf487766a8..8ce25715da 100644--- a/server/internal/handler/comment_duplicate_enqueue_race_test.go+++ b/server/internal/handler/comment_duplicate_enqueue_race_test.go@@ -33,7 +33,9 @@ func dupRaceFixture(t *testing.T, agentName string, issueNumber int) (agentID, i`, testWorkspaceID, testUserID, issueNumber, agentID).Scan(&issueID); err != nil {t.Fatalf("create issue: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM comment WHERE issue_id = $1`, issueID) })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })return agentID, issueID, runtimeID@@ -219,7 +221,9 @@ func TestCommentEnqueueRaceDifferentHeadNotCoalesced(t *testing.T) {`, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {t.Fatalf("seed PR: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID)+ })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {t.Fatalf("link PR: %v", err)@@ -425,7 +429,6 @@ func TestCommentEnqueueRaceQueuedWinnerReattributesOriginator(t *testing.T) {}}-// TestCommentEnqueueRaceNewerDifferentHeadNotDeferred is the regression for Elon// round-5 must-fix: when the different-head task holding the slot is NEWER than// the losing comment (and the comment is not in its planned ids), completion@@ -449,7 +452,9 @@ func TestCommentEnqueueRaceNewerDifferentHeadNotDeferred(t *testing.T) {`, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {t.Fatalf("seed PR: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID)+ })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {t.Fatalf("link PR: %v", err)@@ -525,7 +530,9 @@ func TestCommentEnqueueRaceMixedCoveringAndNewerNotDeferred(t *testing.T) {`, testWorkspaceID, dupRaceHeadB).Scan(&prID); err != nil {t.Fatalf("seed PR: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID)+ })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {t.Fatalf("link PR: %v", err)@@ -636,7 +643,9 @@ func seedDupRacePR(t *testing.T, issueID string, prNumber int) {`, testWorkspaceID, prNumber, dupRaceHeadB).Scan(&prID); err != nil {t.Fatalf("seed PR: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue_pull_request WHERE pull_request_id = $1`, prID)+ })t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM github_pull_request WHERE id = $1`, prID) })if _, err := testPool.Exec(ctx, `INSERT INTO issue_pull_request (issue_id, pull_request_id) VALUES ($1, $2)`, issueID, prID); err != nil {t.Fatalf("link PR: %v", err)diff --git a/server/internal/handler/comment_resolve_test.go b/server/internal/handler/comment_resolve_test.goindex 3465a4038b..a46f0d6f08 100644--- a/server/internal/handler/comment_resolve_test.go+++ b/server/internal/handler/comment_resolve_test.go@@ -204,8 +204,8 @@ func TestResolveComment_ScopedToThread(t *testing.T) {}fx := newResolveTestFixture(t)- resolveCommentHTTP(t, fx.B1) // thread 1 resolution- resolveCommentHTTP(t, fx.A2) // thread 2 resolution — must NOT touch thread 1+ resolveCommentHTTP(t, fx.B1) // thread 1 resolution+ resolveCommentHTTP(t, fx.A2) // thread 2 resolution — must NOT touch thread 1if !commentResolved(t, fx.B1) {t.Fatalf("b1 (thread 1) must stay resolved when a separate thread is resolved")}diff --git a/server/internal/handler/contact_sales_test.go b/server/internal/handler/contact_sales_test.goindex 25e22d1c79..4e934490ea 100644--- a/server/internal/handler/contact_sales_test.go+++ b/server/internal/handler/contact_sales_test.go@@ -167,10 +167,10 @@ func TestIsBusinessEmailDomain(t *testing.T) {func TestCanonicalBusinessEmail(t *testing.T) {cases := []struct {- name string- input string- want string- wantOk bool+ name string+ input string+ want string+ wantOk bool}{{"plain", "[email protected]", "[email protected]", true},{"uppercase normalized", "[email protected]", "[email protected]", true},diff --git a/server/internal/handler/github.go b/server/internal/handler/github.goindex 0ba873f849..f2a100c2a5 100644--- a/server/internal/handler/github.go+++ b/server/internal/handler/github.go@@ -1914,6 +1914,7 @@ func (h *Handler) advanceIssueToDone(ctx context.Context, issue db.Issue, workspprefix := h.getIssuePrefix(ctx, issue.WorkspaceID)resp := issueToResponse(updated, prefix)+ h.fillStatusCategory(ctx, updated.WorkspaceID, &resp)h.publish(protocol.EventIssueUpdated, workspaceID, "system", "", map[string]any{"issue": resp,"status_changed": true,diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex b1f7f63220..3389880623 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -224,60 +224,112 @@ func validateIssueEnum(w http.ResponseWriter, field, value string, allowed []strreturn false}+// fillStatusCategories resolves status_category for responses whose status is+// CUSTOM. The pure builders below fill it for built-in keys — where key IS the+// category — and leave it empty otherwise, so this is the step that makes the+// field authoritative on every payload a client caches or buckets by.+//+// Uses one Resolver for the whole slice: built-in statuses cost no query, and a+// page full of custom ones costs one catalog read rather than one per row. The+// Resolver includes ARCHIVED statuses, because an issue left on an archived+// status still belongs in its category's column. (MUL-6243)+func (h *Handler) fillStatusCategories(ctx context.Context, wsID pgtype.UUID, resps []IssueResponse) {+ fill := h.newStatusCategoryFiller(ctx, wsID)+ for i := range resps {+ fill(&resps[i])+ }+}++// newStatusCategoryFiller returns a request-scoped filler backed by ONE+// Resolver. Reuse it across every response a request builds: the Resolver reads+// the catalog at most once, so a page of custom-status rows costs one query+// rather than one per row. Creating a filler per row would reintroduce the N+1+// this exists to avoid. (MUL-6243)+func (h *Handler) newStatusCategoryFiller(ctx context.Context, wsID pgtype.UUID) func(*IssueResponse) {+ resolver := issuestatus.NewResolver(wsID)+ return func(resp *IssueResponse) {+ if resp == nil || resp.StatusCategory != "" {+ return+ }+ resp.StatusCategory = resolver.Effective(ctx, h.Queries, resp.Status)+ }+}++// fillStatusCategory is the single-response form. Only for endpoints that build+// exactly ONE response; anything looping must use newStatusCategoryFiller.+func (h *Handler) fillStatusCategory(ctx context.Context, wsID pgtype.UUID, resp *IssueResponse) {+ h.newStatusCategoryFiller(ctx, wsID)(resp)+}+func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))+ // A built-in status IS its own category, so this costs no catalog lookup and+ // every response carries it. A CUSTOM status is left empty here and filled+ // in by endpoints that resolve the catalog (see the children endpoints'+ // Resolver); consumers fall back on the same rule. (MUL-6243)+ statusCategory := ""+ if issuestatus.IsBuiltIn(i.Status) {+ statusCategory = i.Status+ }return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}// issueListRowToResponse converts a list-query row (no description) to an IssueResponse.func issueListRowToResponse(i db.ListIssuesRow, issuePrefix string) IssueResponse {+ // Same pure built-in resolution as issueToResponse. (MUL-6243)+ statusCategory := ""+ if issuestatus.IsBuiltIn(i.Status) {+ statusCategory = i.Status+ }identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}@@ -315,30 +367,36 @@ func (h *Handler) labelsByIssue(ctx context.Context, wsUUID pgtype.UUID, issueID}func openIssueRowToResponse(i db.ListOpenIssuesRow, issuePrefix string) IssueResponse {+ // Same pure built-in resolution as issueToResponse. (MUL-6243)+ statusCategory := ""+ if issuestatus.IsBuiltIn(i.Status) {+ statusCategory = i.Status+ }identifier := issuePrefix + "-" + strconv.Itoa(int(i.Number))return IssueResponse{- ID: uuidToString(i.ID),- WorkspaceID: uuidToString(i.WorkspaceID),- Number: i.Number,- Identifier: identifier,- Title: i.Title,- Description: textToPtr(i.Description),- Status: i.Status,- Priority: i.Priority,- AssigneeType: textToPtr(i.AssigneeType),- AssigneeID: uuidToPtr(i.AssigneeID),- CreatorType: i.CreatorType,- CreatorID: uuidToString(i.CreatorID),- ParentIssueID: uuidToPtr(i.ParentIssueID),- ProjectID: uuidToPtr(i.ProjectID),- Position: i.Position,- Stage: int4ToPtr(i.Stage),- StartDate: dateToPtr(i.StartDate),- DueDate: dateToPtr(i.DueDate),- CreatedAt: timestampToString(i.CreatedAt),- UpdatedAt: timestampToString(i.UpdatedAt),- Metadata: parseIssueMetadata(i.Metadata),- Properties: parseIssueProperties(i.Properties),+ ID: uuidToString(i.ID),+ WorkspaceID: uuidToString(i.WorkspaceID),+ Number: i.Number,+ Identifier: identifier,+ Title: i.Title,+ Description: textToPtr(i.Description),+ Status: i.Status,+ StatusCategory: statusCategory,+ Priority: i.Priority,+ AssigneeType: textToPtr(i.AssigneeType),+ AssigneeID: uuidToPtr(i.AssigneeID),+ CreatorType: i.CreatorType,+ CreatorID: uuidToString(i.CreatorID),+ ParentIssueID: uuidToPtr(i.ParentIssueID),+ ProjectID: uuidToPtr(i.ProjectID),+ Position: i.Position,+ Stage: int4ToPtr(i.Stage),+ StartDate: dateToPtr(i.StartDate),+ DueDate: dateToPtr(i.DueDate),+ CreatedAt: timestampToString(i.CreatedAt),+ UpdatedAt: timestampToString(i.UpdatedAt),+ Metadata: parseIssueMetadata(i.Metadata),+ Properties: parseIssueProperties(i.Properties),}}@@ -886,12 +944,14 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {}prefix := h.getIssuePrefix(ctx, wsUUID)+ fillSearch := h.newStatusCategoryFiller(ctx, wsUUID)resp := make([]SearchIssueResponse, len(results))for i, sr := range results {sir := SearchIssueResponse{IssueResponse: issueToResponse(sr.issue, prefix),MatchSource: sr.matchSource,}+ fillSearch(&sir.IssueResponse)// Always populate comment snippet when a matching comment existsif sr.matchedCommentContent != "" {snippet := extractSnippet(sr.matchedCommentContent, q)@@ -1052,9 +1112,11 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {ids[i] = issue.ID}labelsMap := h.labelsByIssue(ctx, wsUUID, ids)+ fillOpen := h.newStatusCategoryFiller(ctx, wsUUID)resp := make([]IssueResponse, len(issues))for i, issue := range issues {resp[i] = openIssueRowToResponse(issue, prefix)+ fillOpen(&resp[i])labels := labelsMap[resp[i].ID]if labels == nil {labels = []LabelResponse{}@@ -1089,6 +1151,14 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {if len(statusesFilter) == 0 {statusesFilter = splitCommaParam(r.URL.Query().Get("status"))}+ // status_category filters by BEHAVIOR rather than by exact key, so one+ // board column can hold a category's canonical status plus every custom+ // status that inherits it. Without this the board would need one column —+ // and one request — per status. (MUL-6243)+ statusCategoriesFilter := splitCommaParam(r.URL.Query().Get("status_categories"))+ if len(statusCategoriesFilter) == 0 {+ statusCategoriesFilter = splitCommaParam(r.URL.Query().Get("status_category"))+ }prioritiesFilter := splitCommaParam(r.URL.Query().Get("priorities"))if len(prioritiesFilter) == 0 {prioritiesFilter = splitCommaParam(r.URL.Query().Get("priority"))@@ -1179,6 +1249,19 @@ func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {return "$" + strconv.Itoa(len(args))}+ if len(statusCategoriesFilter) > 0 {+ // Expanded to concrete status keys rather than filtered through+ // issue_effective_status(): wrapping the column in a function makes the+ // (workspace_id, status) index unusable and turns a two-page index read+ // into a full workspace scan. (MUL-6243)+ keys, err := issuestatus.ExpandCategories(r.Context(), h.Queries, wsUUID, statusCategoriesFilter)+ if err != nil {+ slog.Warn("expand status categories failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to resolve status categories")+ return+ }+ where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(keys)))+ }if len(statusesFilter) > 0 {where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(statusesFilter)))}@@ -1428,6 +1511,7 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)}resp[i].Labels = &labels}+ h.fillStatusCategories(ctx, wsUUID, resp)writeJSON(w, http.StatusOK, map[string]any{"issues": resp,@@ -1642,6 +1726,23 @@ func (h *Handler) ListGroupedIssues(w http.ResponseWriter, r *http.Request) {if len(statuses) > 0 {where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(statuses)))}+ // See ListIssues: category filtering is what lets the board keep a fixed+ // column count as a workspace adds custom statuses. (MUL-6243)+ statusCategories := splitCommaParam(r.URL.Query().Get("status_categories"))+ if len(statusCategories) == 0 {+ statusCategories = splitCommaParam(r.URL.Query().Get("status_category"))+ }+ if len(statusCategories) > 0 {+ // See ListIssues: expanded to keys so the (workspace_id, status) index+ // still drives the scan. (MUL-6243)+ keys, err := issuestatus.ExpandCategories(r.Context(), h.Queries, wsUUID, statusCategories)+ if err != nil {+ slog.Warn("expand status categories failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to resolve status categories")+ return+ }+ where = append(where, fmt.Sprintf("i.status = ANY(%s::text[])", addArg(keys)))+ }priorities := splitCommaParam(r.URL.Query().Get("priorities"))if len(priorities) == 0 {@@ -1994,6 +2095,9 @@ ORDER BY}labelsMap := h.labelsByIssue(ctx, wsUUID, ids)prefix := h.getIssuePrefix(ctx, wsUUID)+ // One Resolver for the whole page — a per-row filler would query the+ // catalog once per custom-status row. (MUL-6243)+ fillGrouped := h.newStatusCategoryFiller(ctx, wsUUID)groups := []IssueAssigneeGroupResponse{}groupIndex := map[string]int{}@@ -2013,6 +2117,7 @@ ORDER BY}issue := issueListRowToResponse(row.ListIssuesRow, prefix)+ fillGrouped(&issue)labels := labelsMap[issue.ID]if labels == nil {labels = []LabelResponse{}@@ -2032,6 +2137,7 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {}prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)resp := issueToResponse(issue, prefix)+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)detailLabels := h.labelsByIssue(r.Context(), issue.WorkspaceID, []pgtype.UUID{issue.ID})[uuidToString(issue.ID)]if detailLabels == nil {detailLabels = []LabelResponse{}@@ -2758,6 +2864,11 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {// payload builder and the HTTP response share the same value.prefix := h.getIssuePrefix(r.Context(), wsUUID)+ // One filler for this create, shared by the broadcast payload and the HTTP+ // response below, so a custom-status create reads the catalog once per+ // request rather than once per payload. (MUL-6243)+ fillCreated := h.newStatusCategoryFiller(r.Context(), wsUUID)+// Analytics agent ID: assignee agent when the issue is being assigned// to an agent, otherwise the creator agent for agent-authored issues.// Resolved here (not in the service) because creator identity is HTTP-side.@@ -2807,6 +2918,12 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {Platform: func() string { p, _, _ := middleware.ClientMetadataFromContext(r.Context()); return p }(),BroadcastPayload: func(issue db.Issue, atts []db.Attachment, labels []db.IssueLabel) map[string]any {payload := issueToResponse(issue, prefix)+ // The event other tabs receive must carry the category too — filling+ // only the HTTP response below is too late for them, and a create+ // they cannot bucket forces a full refetch. Shares one filler with+ // the HTTP response so a custom-status create reads the catalog once+ // per request, not once per payload. (MUL-6243)+ fillCreated(&payload)payload.Attachments = buildAttachmentResponses(atts)// Carry the authoritative label snapshot so every online client// renders the new issue already labeled. Non-nil (even empty)@@ -2821,6 +2938,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {if errors.Is(err, service.ErrActiveDuplicate) {dup := *res.DuplicateIssueexisting := issueToResponse(dup, h.getIssuePrefix(r.Context(), dup.WorkspaceID))+ h.fillStatusCategory(r.Context(), dup.WorkspaceID, &existing)writeJSON(w, http.StatusConflict, map[string]any{"code": "active_duplicate_issue","error": duplicateIssueMessage(existing),@@ -2855,6 +2973,7 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {slog.Info("issue created", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "title", issue.Title, "status", issue.Status, "workspace_id", workspaceID)...)resp := issueToResponse(issue, prefix)+ fillCreated(&resp)resp.Attachments = buildAttachmentResponses(res.Attachments)// Echo the authoritative labels attached in the create transaction. Always// non-nil (empty slice when none) so a newer client can tell the backend@@ -3268,6 +3387,7 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {resp := issueToResponse(issue, prefix)slog.Info("issue updated", append(logger.RequestAttrs(r), "issue_id", id, "workspace_id", workspaceID)...)+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)assigneeChanged := (req.AssigneeType != nil || req.AssigneeID != nil) &&(prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))statusChanged := req.Status != nil && prevIssue.Status != issue.Status@@ -3715,6 +3835,9 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {}updated := 0+ // One Resolver for the whole batch — a per-issue filler would query the+ // catalog once per custom-status row. (MUL-6243)+ fillBatch := h.newStatusCategoryFiller(r.Context(), wsUUID)// Children that transitioned into a terminal status this batch, collected so// the parent/stage notification is evaluated once against the final state// after the loop (MUL-4155) rather than per-child mid-batch.@@ -3897,6 +4020,7 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {resp := issueToResponse(issue, prefix)actorType, actorID := h.resolveActor(r, userID, workspaceID)+ fillBatch(&resp)assigneeChanged := (req.Updates.AssigneeType != nil || req.Updates.AssigneeID != nil) &&(prevIssue.AssigneeType.String != issue.AssigneeType.String || uuidToString(prevIssue.AssigneeID) != uuidToString(issue.AssigneeID))statusChanged := req.Updates.Status != nil && prevIssue.Status != issue.Statusdiff --git a/server/internal/handler/issue_agent_create_e2e_test.go b/server/internal/handler/issue_agent_create_e2e_test.goindex 6eb58cb99f..84cb7a4f11 100644--- a/server/internal/handler/issue_agent_create_e2e_test.go+++ b/server/internal/handler/issue_agent_create_e2e_test.go@@ -83,7 +83,9 @@ func TestAgentCreateOriginator_E2E_CreateAssignSquad_PrivateWorkerTriggered(t *t`, creatorAID, ownerH).Scan(&creatorTaskID); err != nil {t.Fatalf("create A's acting task: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, creatorTaskID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, creatorTaskID)+ })// Step 1: agent A creates an issue through the ordinary create path and// assigns it to the private-leader squad in the same call.@@ -203,7 +205,9 @@ func TestAgentCreateOriginator_E2E_UpdateAssignSquad_HandlerGateAdmitsPrivateLea`, creatorAID, ownerH).Scan(&creatorTaskID); err != nil {t.Fatalf("create A's acting task: %v", err)}- t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, creatorTaskID) })+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, creatorTaskID)+ })// Agent A creates an unassigned issue via the ordinary path.w := httptest.NewRecorder()diff --git a/server/internal/handler/issue_status.go b/server/internal/handler/issue_status.goindex 0e97f63c36..975332a7bb 100644--- a/server/internal/handler/issue_status.go+++ b/server/internal/handler/issue_status.go@@ -295,13 +295,17 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {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)+ // Archiving retires a status from FUTURE use and deliberately leaves issues+ // already on it untouched: they keep their status, keep rendering, and keep+ // resolving to their category's behavior (issuestatus.Effective ignores+ // archived_at on purpose). Forcing a migration first would mean rewriting+ // history to retire a label.+ //+ // The EXCLUSIVE catalog lock is still taken, and it is what makes "no NEW+ // issue can be assigned an archived status" exact rather than approximate:+ // an issue write targeting a custom status re-resolves it under the SHARED+ // side of this lock (assertIssueStatusStillActive), so a write can never+ // interleave between this archive and its own status check. (MUL-6243)tx, err := h.TxStarter.Begin(r.Context())if err != nil {slog.Warn("ArchiveIssueStatus begin failed", append(logger.RequestAttrs(r), "error", err)...)@@ -317,21 +321,6 @@ func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {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,diff --git a/server/internal/handler/issue_status_test.go b/server/internal/handler/issue_status_test.goindex 1a216a8be3..e3ec18ebd3 100644--- a/server/internal/handler/issue_status_test.go+++ b/server/internal/handler/issue_status_test.go@@ -3,14 +3,19 @@ package handlerimport ("context""encoding/json"+ "fmt""net/http""net/http/httptest"+ "slices""testing""time""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/issuestatus"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol")// Issue status catalog tests (MUL-6243).@@ -282,48 +287,41 @@ func TestBuiltInStatusesAreImmutable(t *testing.T) {})}-// TestArchiveRefusesWhileIssuesStillUseTheStatus is the decision recorded on-// the issue: migrate the issues first rather than silently rewriting them.-func TestArchiveRefusesWhileIssuesStillUseTheStatus(t *testing.T) {+// TestArchiveRetiresStatusWithoutTouchingExistingIssues pins the archive rule:+// archiving retires a status from FUTURE use only. Issues already on it keep it+// and keep behaving as their category prescribes — retiring a label must not+// rewrite history.+func TestArchiveRetiresStatusWithoutTouchingExistingIssues(t *testing.T) {ctx := context.Background()entry := createTestCustomStatus(t, "in_use_a", issuestatus.InProgress)+ issueID := mustCreateIssue(t, "occupies the status", "in_use_a")- 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"`+ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("archiving an in-use status should succeed, got %d", code)}- 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())+ // The existing issue keeps the archived status verbatim.+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM issue WHERE id = $1`, issueID).Scan(&status); err != nil {+ t.Fatalf("read back: %v", err)+ }+ if status != "in_use_a" {+ t.Errorf("existing issue status = %q, want it left on the archived status", status)}- // 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)+ // And it still resolves to its category, so its platform behavior is+ // unchanged — Effective deliberately ignores archived_at.+ if got := issuestatus.Effective(ctx, testHandler.Queries, parseUUID(testWorkspaceID), "in_use_a"); got != issuestatus.InProgress {+ t.Errorf("Effective on an archived status = %q, want %q", got, issuestatus.InProgress)}- 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())++ // But nothing NEW can be assigned to it.+ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "should be refused", "status": "in_use_a",+ }))+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 assigning an archived status to a new issue, got %d: %s", rec.Code, rec.Body.String())}}@@ -638,11 +636,12 @@ func TestWritesRejectAnArchivedStatus(t *testing.T) {}-// 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) {+// TestArchiveSucceedsAfterACommittedWrite is the other ordering: an issue+// committed on the status does not block archiving it, because archiving only+// retires it from future use.+func TestArchiveSucceedsAfterACommittedWrite(t *testing.T) {ctx := context.Background()- t.Run("writer wins: archive refuses with conflict", func(t *testing.T) {+ t.Run("writer wins: archive still succeeds and leaves the issue alone", func(t *testing.T) {entry := createTestCustomStatus(t, "race_b_writer", issuestatus.InProgress)rec := httptest.NewRecorder()@@ -658,8 +657,16 @@ func TestArchiveRefusesAfterACommittedWrite(t *testing.T) {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)+ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("archive after a committed write = %d, want 200", code)+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM issue WHERE id = $1`,+ parseUUID(created.ID)).Scan(&status); err != nil {+ t.Fatalf("read back: %v", err)+ }+ if status != "race_b_writer" {+ t.Errorf("issue status = %q, want it untouched by the archive", status)}})@@ -955,3 +962,273 @@ func TestChildrenResponseCarriesStatusCategory(t *testing.T) {t.Errorf("status_category = %q, want %q", payload.Issues[0].StatusCategory, "done")}}++// TestCategoryFilterExpandsToIndexedStatusKeys is the regression guard for the+// performance fix: filtering by category must expand to concrete status keys so+// `status = ANY(...)` can use the (workspace_id, status) index. Wrapping the+// column in issue_effective_status() made that index unusable and turned a+// two-page index read into a full workspace scan.+func TestCategoryFilterExpandsToIndexedStatusKeys(t *testing.T) {+ ctx := context.Background()+ seedTestCatalog(t)+ ws := parseUUID(testWorkspaceID)++ t.Run("built-in category expands to exactly its own key", func(t *testing.T) {+ keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, ws, []string{"blocked"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if len(keys) != 1 || keys[0] != "blocked" {+ t.Errorf("expand(blocked) = %v, want exactly [blocked] — a workspace with no "++ "custom statuses must produce the pre-feature query", keys)+ }+ })++ t.Run("category includes its custom statuses", func(t *testing.T) {+ createTestCustomStatus(t, "human_review_x", issuestatus.InReview)+ keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, ws, []string{"in_review"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if !slices.Contains(keys, "in_review") || !slices.Contains(keys, "human_review_x") {+ t.Errorf("expand(in_review) = %v, want both the canonical and the custom key", keys)+ }+ })++ // An issue left on an archived status still belongs in its category's+ // column, so the expansion must keep archived keys.+ t.Run("archived statuses stay in their category", func(t *testing.T) {+ entry := createTestCustomStatus(t, "retired_x", issuestatus.Done)+ if code := archiveStatusVia(t, entry); code != http.StatusOK {+ t.Fatalf("archive: %d", code)+ }+ keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, ws, []string{"done"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if !slices.Contains(keys, "retired_x") {+ t.Errorf("expand(done) = %v, want the archived key included so issues on it "++ "still appear in the Done column", keys)+ }+ })++ // A workspace whose seed has not landed must still filter correctly.+ t.Run("unseeded workspace falls back to the canonical keys", func(t *testing.T) {+ if _, err := testPool.Exec(ctx, `DELETE FROM issue_status WHERE workspace_id = $1`, ws); err != nil {+ t.Fatalf("clear catalog: %v", err)+ }+ t.Cleanup(func() { seedTestCatalog(t) })+ keys, err := issuestatus.ExpandCategories(ctx, testHandler.Queries, ws, []string{"todo", "done"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if len(keys) != 2 || !slices.Contains(keys, "todo") || !slices.Contains(keys, "done") {+ t.Errorf("expand on an unseeded workspace = %v, want [todo done]", keys)+ }+ })+}++// TestListFilterByCategoryReturnsCustomStatusIssues exercises the real endpoint.+func TestListFilterByCategoryReturnsCustomStatusIssues(t *testing.T) {+ ctx := context.Background()+ createTestCustomStatus(t, "human_review_l", issuestatus.InReview)+ customID := mustCreateIssue(t, "custom in review", "human_review_l")+ builtinID := mustCreateIssue(t, "builtin in review", "in_review")+ otherID := mustCreateIssue(t, "unrelated todo", "todo")+ _ = ctx++ rec := httptest.NewRecorder()+ testHandler.ListIssues(rec, newRequest(http.MethodGet, "/api/issues?status_category=in_review&limit=100", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("list: %d %s", rec.Code, rec.Body.String())+ }+ var payload struct {+ Issues []struct {+ ID string `json:"id"`+ 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)+ }+ got := map[string]string{}+ for _, i := range payload.Issues {+ got[i.ID] = i.StatusCategory+ }+ if _, ok := got[uuidToString(customID)]; !ok {+ t.Error("the in_review category must include issues on a custom in_review status")+ }+ if _, ok := got[uuidToString(builtinID)]; !ok {+ t.Error("the in_review category must include issues on the built-in status")+ }+ if _, ok := got[uuidToString(otherID)]; ok {+ t.Error("the in_review category must not include a todo issue")+ }+ // Every row carries an authoritative category, custom statuses included —+ // this is what the client buckets and caches by.+ if c := got[uuidToString(customID)]; c != "in_review" {+ t.Errorf("custom-status row status_category = %q, want %q", c, "in_review")+ }+}++// TestCreateEventCarriesCustomStatusCategory is the regression guard for the+// websocket path: filling the category only on the HTTP response is too late+// for other tabs, which receive the broadcast payload. Without it they cannot+// bucket the new issue and must fall back to a full refetch.+func TestCreateEventCarriesCustomStatusCategory(t *testing.T) {+ createTestCustomStatus(t, "human_review_ev", issuestatus.InReview)++ gotEvent := make(chan events.Event, 1)+ testHandler.Bus.Subscribe(protocol.EventIssueCreated, func(e events.Event) {+ select {+ case gotEvent <- e:+ default:+ }+ })++ rec := httptest.NewRecorder()+ testHandler.CreateIssue(rec, newRequest(http.MethodPost, "/api/issues", map[string]any{+ "title": "custom status event", "status": "human_review_ev",+ }))+ if rec.Code != http.StatusCreated {+ t.Fatalf("create: %d %s", rec.Code, rec.Body.String())+ }+ var created struct {+ ID string `json:"id"`+ StatusCategory string `json:"status_category"`+ }+ json.Unmarshal(rec.Body.Bytes(), &created)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, parseUUID(created.ID))+ })+ if created.StatusCategory != "in_review" {+ t.Errorf("HTTP response status_category = %q, want in_review", created.StatusCategory)+ }++ select {+ case e := <-gotEvent:+ payload, ok := e.Payload.(map[string]any)+ if !ok {+ t.Fatalf("event payload shape: %T", e.Payload)+ }+ issue, ok := payload["issue"].(IssueResponse)+ if !ok {+ t.Fatalf("event issue shape: %T", payload["issue"])+ }+ if issue.StatusCategory != "in_review" {+ t.Errorf("event status_category = %q, want in_review — other tabs cannot "++ "bucket the new issue without it", issue.StatusCategory)+ }+ case <-time.After(3 * time.Second):+ t.Fatal("no issue:created event")+ }+}++// TestListEndpointsCarryStatusCategory covers the remaining payload exits: every+// row a list or get returns must carry an authoritative category, custom+// statuses included. It deliberately does NOT assert the per-request catalog+// read count — see the note on the resolver subtest below for why.+func TestListEndpointsCarryStatusCategory(t *testing.T) {+ createTestCustomStatus(t, "human_review_n", issuestatus.InReview)+ for i := range 3 {+ mustCreateIssue(t, fmt.Sprintf("n+1 probe %d", i), "human_review_n")+ }++ t.Run("list carries category for every custom row", func(t *testing.T) {+ rec := httptest.NewRecorder()+ testHandler.ListIssues(rec, newRequest(http.MethodGet, "/api/issues?status_category=in_review&limit=100", nil))+ if rec.Code != http.StatusOK {+ t.Fatalf("list: %d %s", rec.Code, rec.Body.String())+ }+ var payload struct {+ Issues []struct {+ Status string `json:"status"`+ StatusCategory string `json:"status_category"`+ } `json:"issues"`+ }+ json.Unmarshal(rec.Body.Bytes(), &payload)+ seen := 0+ for _, i := range payload.Issues {+ if i.Status == "human_review_n" {+ seen+++ if i.StatusCategory != "in_review" {+ t.Errorf("custom row status_category = %q, want in_review", i.StatusCategory)+ }+ }+ }+ if seen < 3 {+ t.Errorf("expected the 3 custom-status rows in the in_review category, saw %d", seen)+ }+ })++ // NOTE ON COVERAGE: there is deliberately no assertion here that the handler+ // reads the catalog only once per page. pg_stat_user_tables counters lag+ // behind the queries that produced them, so a delta around one request does+ // not reliably distinguish one read from N — a threshold written against it+ // passes even with a per-row filler, which would make this test claim more+ // than it proves. Observing it properly needs a counting Querier injected+ // into the handler, which it does not support today.+ //+ // What IS pinned: the Resolver amortizes reads (below), and every list site+ // constructs its filler OUTSIDE the loop, which is what makes that+ // amortization reach the handler.+ t.Run("the resolver amortizes repeated lookups", func(t *testing.T) {+ r := issuestatus.NewResolver(parseUUID(testWorkspaceID))+ ctx := context.Background()+ for range 10 {+ if got := r.Effective(ctx, testHandler.Queries, "human_review_n"); got != "in_review" {+ t.Fatalf("Effective = %q, want in_review", got)+ }+ }+ })++ t.Run("get carries category", func(t *testing.T) {+ id := mustCreateIssue(t, "get carries category", "human_review_n")+ rec := httptest.NewRecorder()+ testHandler.GetIssue(rec, withURLParam(+ newRequest(http.MethodGet, "/api/issues/"+uuidToString(id), nil), "id", uuidToString(id)))+ if rec.Code != http.StatusOK {+ t.Fatalf("get: %d %s", rec.Code, rec.Body.String())+ }+ var got struct {+ StatusCategory string `json:"status_category"`+ }+ json.Unmarshal(rec.Body.Bytes(), &got)+ if got.StatusCategory != "in_review" {+ t.Errorf("GetIssue status_category = %q, want in_review", got.StatusCategory)+ }+ })+}++// TestBackgroundEventCarriesCustomStatusCategory pins the background-event+// payload. IssueToMap fills a category only for built-ins; the publishers that+// can emit a CUSTOM status go through IssueToMapWithCategory so clients receive+// an authoritative one instead of a blank they would have to refetch to resolve.+func TestBackgroundEventCarriesCustomStatusCategory(t *testing.T) {+ ctx := context.Background()+ createTestCustomStatus(t, "human_review_bg", issuestatus.InReview)+ id := mustCreateIssue(t, "background event category", "human_review_bg")++ issue, err := testHandler.Queries.GetIssue(ctx, id)+ if err != nil {+ t.Fatalf("load issue: %v", err)+ }++ // Plain IssueToMap leaves a custom status uncategorized — that is why the+ // publishers use the WithCategory form.+ plain := service.IssueToMap(issue, "MUL")+ if plain["status_category"] != "" {+ t.Errorf("IssueToMap custom status_category = %v, want empty (no catalog access)",+ plain["status_category"])+ }++ authoritative := service.IssueToMapWithCategory(ctx, testHandler.Queries, issue, "MUL")+ if authoritative["status_category"] != "in_review" {+ t.Errorf("IssueToMapWithCategory status_category = %v, want in_review",+ authoritative["status_category"])+ }+ if authoritative["status"] != "human_review_bg" {+ t.Errorf("status = %v, want the custom key verbatim", authoritative["status"])+ }+}diff --git a/server/internal/handler/issue_table_rows.go b/server/internal/handler/issue_table_rows.goindex b0f8002855..f22ea5834b 100644--- a/server/internal/handler/issue_table_rows.go+++ b/server/internal/handler/issue_table_rows.go@@ -458,9 +458,12 @@ SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority,issueIDs[index] = row.issue.ID}labelsByIssue := baseHandler.labelsByIssue(r.Context(), compiled.workspaceID, issueIDs)+ // One Resolver for the page — see newStatusCategoryFiller. (MUL-6243)+ fillTableRow := baseHandler.newStatusCategoryFiller(r.Context(), compiled.workspaceID)responseRows := make([]issueTableRowResponse, len(scanned))for index, row := range scanned {issue := issueListRowToResponse(row.issue, prefix)+ fillTableRow(&issue)labels := labelsByIssue[issue.ID]if labels == nil {labels = []LabelResponse{}diff --git a/server/internal/handler/issue_view_test.go b/server/internal/handler/issue_view_test.goindex 05674f61a5..62aeac376a 100644--- a/server/internal/handler/issue_view_test.go+++ b/server/internal/handler/issue_view_test.go@@ -1,14 +1,13 @@package handlerimport (- "strings""context""encoding/json""fmt""net/http""net/http/httptest"+ "strings""testing"-)func createIssueViewForTest(t *testing.T, body map[string]any) (IssueViewResponse, int, string) {diff --git a/server/internal/handler/onboarding_shim.go b/server/internal/handler/onboarding_shim.goindex 1ba3327276..f461c4f1fe 100644--- a/server/internal/handler/onboarding_shim.go+++ b/server/internal/handler/onboarding_shim.go@@ -314,6 +314,7 @@ func (h *Handler) BootstrapOnboardingRuntime(w http.ResponseWriter, r *http.Requif issueCreated {prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)resp := issueToResponse(issue, prefix)+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": resp})platform, _, _ := middleware.ClientMetadataFromContext(r.Context())obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(@@ -454,6 +455,7 @@ func (h *Handler) BootstrapOnboardingNoRuntime(w http.ResponseWriter, r *http.Reif issueCreated {prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)resp := issueToResponse(issue, prefix)+ h.fillStatusCategory(r.Context(), issue.WorkspaceID, &resp)h.publish(protocol.EventIssueCreated, req.WorkspaceID, "member", userID, map[string]any{"issue": resp})platform2, _, _ := middleware.ClientMetadataFromContext(r.Context())obsmetrics.RecordEvent(h.Analytics, h.Metrics, analytics.IssueCreated(diff --git a/server/internal/handler/share_link.go b/server/internal/handler/share_link.goindex 35ca73a62a..8c3fc0945e 100644--- a/server/internal/handler/share_link.go+++ b/server/internal/handler/share_link.go@@ -393,16 +393,16 @@ func shareLinkListToResponse(row db.ListShareLinksByWorkspaceRow) ShareLinkRespomaxUses = &row.MaxUses.Int32}return ShareLinkResponse{- ID: uuidToString(row.ID),- WorkspaceID: uuidToString(row.WorkspaceID),- Code: row.Code,- CreatedBy: uuidToString(row.CreatedBy),- Role: row.Role,- ExpiresAt: expiresAt,- MaxUses: maxUses,- UseCount: row.UseCount,- IsActive: row.IsActive,- CreatedAt: timestampToString(row.CreatedAt),+ ID: uuidToString(row.ID),+ WorkspaceID: uuidToString(row.WorkspaceID),+ Code: row.Code,+ CreatedBy: uuidToString(row.CreatedBy),+ Role: row.Role,+ ExpiresAt: expiresAt,+ MaxUses: maxUses,+ UseCount: row.UseCount,+ IsActive: row.IsActive,+ CreatedAt: timestampToString(row.CreatedAt),CreatorName: row.CreatorName,CreatorEmail: row.CreatorEmail,}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 4e31ffb763..90b565c154 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -899,6 +899,9 @@ func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, oriopts := service.IssueCreateOpts{AssignedAgentRunFireAt: assignedRunFireAt,BroadcastPayload: func(issue db.Issue, _ []db.Attachment, _ []db.IssueLabel) map[string]any {+ // Plain IssueToMap is authoritative here: this path always creates+ // with the built-in "todo" above, and a built-in status IS its own+ // category, so no catalog read is possible or needed. (MUL-6243)return map[string]any{"issue": service.IssueToMap(issue, issuePrefix)}},}diff --git a/server/internal/issuestatus/issuestatus.go b/server/internal/issuestatus/issuestatus.goindex 04b9b60590..a3c0c3673d 100644--- a/server/internal/issuestatus/issuestatus.go+++ b/server/internal/issuestatus/issuestatus.go@@ -85,6 +85,7 @@ 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+ ListIssueStatusKeysByCategories(ctx context.Context, arg db.ListIssueStatusKeysByCategoriesParams) ([]string, error)}// Canonical returns the 7 built-in status keys in display order.@@ -317,3 +318,55 @@ func (r *Resolver) Effective(ctx context.Context, q Querier, status string) stri}return category}++// ExpandCategories turns a set of categories into the status keys that belong+// to them, for use as an INDEXED `status = ANY(...)` predicate.+//+// This exists instead of filtering on issue_effective_status(workspace, status):+// wrapping the column in a function makes the (workspace_id, status) index+// unusable, turning a two-page index read into a full workspace scan. Expanding+// first keeps the original access path — and for a workspace with no custom+// statuses each category expands to exactly its own key, so the query is+// byte-for-byte the one that ran before this feature.+//+// Archived statuses are included: archiving stops FUTURE assignment but leaves+// existing issues in place, and those issues must still appear in their+// category's column.+//+// An unseeded workspace yields no rows; the categories themselves are returned+// in that case, which is correct because a built-in key IS its own category.+func ExpandCategories(ctx context.Context, q Querier, workspaceID pgtype.UUID, categories []string) ([]string, error) {+ valid := make([]string, 0, len(categories))+ for _, c := range categories {+ if IsCategory(c) {+ valid = append(valid, c)+ }+ }+ if len(valid) == 0 {+ return nil, nil+ }+ keys, err := q.ListIssueStatusKeysByCategories(ctx, db.ListIssueStatusKeysByCategoriesParams{+ WorkspaceID: workspaceID,+ Categories: valid,+ })+ if err != nil {+ return nil, err+ }+ seen := make(map[string]bool, len(keys)+len(valid))+ out := make([]string, 0, len(keys)+len(valid))+ for _, k := range keys {+ if !seen[k] {+ seen[k] = true+ out = append(out, k)+ }+ }+ // A category always contains at least its own canonical key, even if the+ // catalog row is missing (unseeded workspace, mid-rollout).+ for _, c := range valid {+ if !seen[c] {+ seen[c] = true+ out = append(out, c)+ }+ }+ return out, nil+}diff --git a/server/internal/issuestatus/issuestatus_test.go b/server/internal/issuestatus/issuestatus_test.goindex ed3526160e..07f6c787ba 100644--- a/server/internal/issuestatus/issuestatus_test.go+++ b/server/internal/issuestatus/issuestatus_test.go@@ -61,6 +61,23 @@ func (f *fakeQuerier) SeedIssueStatusEntries(_ context.Context, _ pgtype.UUID) ereturn f.err}+func (f *fakeQuerier) ListIssueStatusKeysByCategories(_ context.Context, arg db.ListIssueStatusKeysByCategoriesParams) ([]string, error) {+ if f.err != nil {+ return nil, f.err+ }+ wanted := map[string]bool{}+ for _, c := range arg.Categories {+ wanted[c] = true+ }+ var out []string+ for _, e := range f.entries {+ if wanted[e.Category] {+ out = append(out, e.Key)+ }+ }+ return out, nil+}+func custom(key, category string) db.IssueStatus {return db.IssueStatus{Key: key, Category: category, WorkspaceID: testWorkspace}}@@ -309,3 +326,41 @@ func TestResolverFailsSafeWhenTheCatalogReadFails(t *testing.T) {t.Errorf("Effective on a failed catalog read = %q, want the key unchanged", got)}}++// ExpandCategories is what keeps the (workspace_id, status) index usable for a+// category filter; wrapping the column in issue_effective_status() instead made+// it a full workspace scan.+func TestExpandCategories(t *testing.T) {+ ctx := context.Background()++ t.Run("no catalog rows still yields the canonical keys", func(t *testing.T) {+ got, err := ExpandCategories(ctx, newFakeQuerier(), testWorkspace, []string{"blocked"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if len(got) != 1 || got[0] != "blocked" {+ t.Errorf("expand(blocked) on an empty catalog = %v, want [blocked]", got)+ }+ })++ t.Run("includes custom keys and never duplicates the canonical one", func(t *testing.T) {+ q := newFakeQuerier(custom("in_review", InReview), custom("human_review", InReview))+ got, err := ExpandCategories(ctx, q, testWorkspace, []string{"in_review"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if len(got) != 2 {+ t.Fatalf("expand(in_review) = %v, want exactly 2 keys with no duplicate", got)+ }+ })++ t.Run("ignores values that are not categories", func(t *testing.T) {+ got, err := ExpandCategories(ctx, newFakeQuerier(), testWorkspace, []string{"not_a_category"})+ if err != nil {+ t.Fatalf("expand: %v", err)+ }+ if got != nil {+ t.Errorf("expand of a non-category = %v, want nil", got)+ }+ })+}diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.goindex 7bf7557902..63360ab91b 100644--- a/server/internal/service/autopilot.go+++ b/server/internal/service/autopilot.go@@ -692,7 +692,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.AutopiActorType: "agent",ActorID: util.UUIDToString(leader.ID),Payload: map[string]any{- "issue": IssueToMap(issue, prefix),+ "issue": IssueToMapWithCategory(ctx, s.Queries, issue, prefix),},})s.captureIssueCreatedFromAutopilot(ap, run, issue, leader.ID)diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex bcaefca4ed..04d4eb046d 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -549,7 +549,7 @@ func (s *IssueService) PublishAttachmentsChanged(ctx context.Context, issue db.IActorType: "member",ActorID: util.UUIDToString(actorID),Payload: map[string]any{- "issue": IssueToMap(current, workspace.IssuePrefix),+ "issue": IssueToMapWithCategory(ctx, s.Queries, current, workspace.IssuePrefix),"assignee_changed": false,"status_changed": false,"project_changed": false,diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 1b36ee7417..8abd93f396 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -4794,7 +4794,7 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas// it here too. Without it the board / status-filter// caches keep showing the issue as in_progress until// the next write touches it (#4648 / MUL-3782).- s.broadcastIssueUpdated(updatedIssue, issue.Status)+ s.broadcastIssueUpdated(ctx, updatedIssue, issue.Status)}}}@@ -5403,7 +5403,7 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQu// emit status-change activity / notifications. That is intentional for the// realtime-staleness fix (#4648 / MUL-3782); folding those side effects in// would mean unifying the payload type and is left as a follow-up.-func (s *TaskService) broadcastIssueUpdated(issue db.Issue, prevStatus string) {+func (s *TaskService) broadcastIssueUpdated(ctx context.Context, issue db.Issue, prevStatus string) {prefix := s.getIssuePrefix(issue.WorkspaceID)s.Bus.Publish(events.Event{Type: protocol.EventIssueUpdated,@@ -5411,7 +5411,7 @@ func (s *TaskService) broadcastIssueUpdated(issue db.Issue, prevStatus string) {ActorType: "system",ActorID: "",Payload: map[string]any{- "issue": IssueToMap(issue, prefix),+ "issue": IssueToMapWithCategory(ctx, s.Queries, issue, prefix),"status_changed": prevStatus != issue.Status,"prev_status": prevStatus,},@@ -5539,15 +5539,38 @@ func (s *TaskService) AutoUnresolveThreadOnReply(ctx context.Context, parent *db// field missing here is a field that reads back undefined until the next// refetch — see TestIssueToMap_KeysMatchIssueResponse, which fails if the two// renderings drift apart.+// builtInStatusCategory returns a status's category when it can be known+// without a catalog read — i.e. for the 7 built-ins, where key == category.+func builtInStatusCategory(status string) string {+ if issuestatus.IsBuiltIn(status) {+ return status+ }+ return ""+}++// IssueToMapWithCategory is IssueToMap with an AUTHORITATIVE status_category,+// resolved through the catalog so a custom status is not emitted with a blank+// one. Background events go through here; clients treat this payload as a+// complete issue and bucket it by category. (MUL-6243)+func IssueToMapWithCategory(ctx context.Context, q issuestatus.Querier, issue db.Issue, issuePrefix string) map[string]any {+ m := IssueToMap(issue, issuePrefix)+ m["status_category"] = issuestatus.Effective(ctx, q, issue.WorkspaceID, issue.Status)+ return m+}+func IssueToMap(issue db.Issue, issuePrefix string) map[string]any {return map[string]any{- "id": util.UUIDToString(issue.ID),- "workspace_id": util.UUIDToString(issue.WorkspaceID),- "number": issue.Number,- "identifier": IssueIdentifier(issuePrefix, issue.Number),- "title": issue.Title,- "description": util.TextToPtr(issue.Description),- "status": issue.Status,+ "id": util.UUIDToString(issue.ID),+ "workspace_id": util.UUIDToString(issue.WorkspaceID),+ "number": issue.Number,+ "identifier": IssueIdentifier(issuePrefix, issue.Number),+ "title": issue.Title,+ "description": util.TextToPtr(issue.Description),+ "status": issue.Status,+ // Mirrors handler.IssueResponse.StatusCategory: a built-in status IS+ // its own category, so this resolves with no catalog lookup. Empty for+ // a custom status, which consumers resolve via the catalog. (MUL-6243)+ "status_category": builtInStatusCategory(issue.Status),"priority": issue.Priority,"assignee_type": util.TextToPtr(issue.AssigneeType),"assignee_id": util.UUIDToPtr(issue.AssigneeID),diff --git a/server/internal/service/task_issue_broadcast_test.go b/server/internal/service/task_issue_broadcast_test.goindex e74a834c21..d6941a46c2 100644--- a/server/internal/service/task_issue_broadcast_test.go+++ b/server/internal/service/task_issue_broadcast_test.go@@ -51,7 +51,7 @@ func TestBroadcastIssueUpdated_EmitsStatusChange(t *testing.T) {Number: 7,Status: "todo",}- svc.broadcastIssueUpdated(issue, "in_progress")+ svc.broadcastIssueUpdated(context.Background(), issue, "in_progress")if len(got) != 1 {t.Fatalf("expected exactly 1 published event, got %d", len(got))@@ -104,7 +104,7 @@ func TestBroadcastIssueUpdated_NoStatusChange(t *testing.T) {WorkspaceID: testUUID(2),Status: "todo",}- svc.broadcastIssueUpdated(issue, "todo")+ svc.broadcastIssueUpdated(context.Background(), issue, "todo")if len(got) != 1 {t.Fatalf("expected exactly 1 published event, got %d", len(got))diff --git a/server/pkg/db/generated/issue_status.sql.go b/server/pkg/db/generated/issue_status.sql.goindex 1af7310a03..254224591f 100644--- a/server/pkg/db/generated/issue_status.sql.go+++ b/server/pkg/db/generated/issue_status.sql.go@@ -28,8 +28,11 @@ type ArchiveIssueStatusEntryParams struct {}// 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.+// category's behavior definition.+//+// Archiving retires a status from future use only. Issues already on it keep+// it — Effective ignores archived_at, so their behavior is unchanged — while+// Resolve rejects it, so nothing new can be assigned to it.func (q *Queries) ArchiveIssueStatusEntry(ctx context.Context, arg ArchiveIssueStatusEntryParams) (IssueStatus, error) {row := q.db.QueryRow(ctx, archiveIssueStatusEntry, arg.ID, arg.WorkspaceID)var i IssueStatus@@ -61,6 +64,9 @@ type CountIssuesUsingStatusKeyParams struct {Key string `json:"key"`}+// Reported alongside a status so the UI can say how many issues still carry an+// archived one. NOT an archive precondition: archiving never requires migrating+// issues off the status.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@@ -257,6 +263,45 @@ func (q *Queries) ListIssueStatusEntries(ctx context.Context, arg ListIssueStatureturn items, nil}+const listIssueStatusKeysByCategories = `-- name: ListIssueStatusKeysByCategories :many+SELECT key FROM issue_status+WHERE workspace_id = $1::uuid+ AND category = ANY($2::text[])+`++type ListIssueStatusKeysByCategoriesParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Categories []string `json:"categories"`+}++// Expands a set of categories to the status keys that belong to them, so a+// category filter can be applied as an INDEXED `status = ANY(...)` predicate+// instead of wrapping the column in issue_effective_status(), which makes+// (workspace_id, status) unusable and forces a full workspace scan.+//+// ARCHIVED statuses are included on purpose: archiving retires a status from+// future assignment but leaves existing issues on it, and those issues must+// still appear in their category's column.+func (q *Queries) ListIssueStatusKeysByCategories(ctx context.Context, arg ListIssueStatusKeysByCategoriesParams) ([]string, error) {+ rows, err := q.db.Query(ctx, listIssueStatusKeysByCategories, arg.WorkspaceID, arg.Categories)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []string{}+ for rows.Next() {+ var key string+ if err := rows.Scan(&key); err != nil {+ return nil, err+ }+ items = append(items, key)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const lockIssueStatusCatalog = `-- name: LockIssueStatusCatalog :execSELECT pg_advisory_xact_lock(hashtextextended($1::uuid::text || ':issue_status', 0))`diff --git a/server/pkg/db/queries/issue_status.sql b/server/pkg/db/queries/issue_status.sqlindex 027e5d9044..5412ddff16 100644--- a/server/pkg/db/queries/issue_status.sql+++ b/server/pkg/db/queries/issue_status.sql@@ -88,8 +88,11 @@ 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.+-- category's behavior definition.+--+-- Archiving retires a status from future use only. Issues already on it keep+-- 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 SETarchived_at = now(),updated_at = now()@@ -100,6 +103,9 @@ WHERE id = sqlc.arg('id')::uuidRETURNING *;-- name: CountIssuesUsingStatusKey :one+-- Reported alongside a status so the UI can say how many issues still carry an+-- archived one. NOT an archive precondition: archiving never requires migrating+-- issues off the status.SELECT COUNT(*)::bigint FROM issueWHERE workspace_id = sqlc.arg('workspace_id')::uuidAND status = sqlc.arg('key')::text;@@ -124,3 +130,16 @@ SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg('workspace_id')::uuid::te-- 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));++-- name: ListIssueStatusKeysByCategories :many+-- Expands a set of categories to the status keys that belong to them, so a+-- category filter can be applied as an INDEXED `status = ANY(...)` predicate+-- instead of wrapping the column in issue_effective_status(), which makes+-- (workspace_id, status) unusable and forces a full workspace scan.+--+-- ARCHIVED statuses are included on purpose: archiving retires a status from+-- future assignment but leaves existing issues on it, and those issues must+-- still appear in their category's column.+SELECT key FROM issue_status+WHERE workspace_id = sqlc.arg('workspace_id')::uuid+ AND category = ANY(sqlc.arg('categories')::text[]);