Files
da1671ca20 MUL-7420: Project workflows — columns and handoffs on the workflow (#8814)
* feat(workflows): workspace workflows with step handoffs (MUL-7420)

A workflow is a named, workspace-level selection of statuses from the
shared status catalog, in board order, with an optional handoff on each
step. Projects opt in through project.workflow_id; a project without one
keeps the whole catalog (the implicit Default workflow), so existing
workspaces see no change.

- issue_workflow table + project.workflow_id, CRUD API under
  /api/issue-workflows, POST /api/projects/{id}/workflow with a dry-run
  status mapping plan. Only issues on statuses the target workflow does
  not list are remapped, and remapping never hands issues off.
- Issue writes keep the status inside the project's workflow. Entering a
  step with a handler through a status change assigns the issue to that
  handler and starts its run with the step's brief as the handoff note;
  an explicit assignee in the same write wins. Creating an issue starts
  at the workflow's starting step.
- Task claims carry the issue's project workflow, and the brief renders
  a Project Workflow section so agents move along this project's
  statuses instead of the built-in ones.
- Statuses a workflow lists cannot be archived.
- Adoption is gated by the project_workflows_v1 flag; existing
  workflows keep working and projects can always switch back to Default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): workflow settings, project picker and workflow-aware boards (MUL-7420)

- Settings → Workflows (behind project_workflows_v1): the Default
  workflow plus named workflows, each shown as its step chain with
  handlers and the projects using it; an editor to pick statuses from the
  library, order them, mark the starting step, and set each step's
  handoff, instructions and next/back statuses.
- Project Workflow property: switching dry-runs first and asks where
  issues on unlisted statuses go; nothing else moves and nothing is
  handed off.
- A project board's columns are its workflow's steps, and each column
  head names who entering it hands the issue to.
- Status pickers offer only the issue's workflow steps and say who each
  hands off to; boards refuse drops onto statuses the dragged card's
  workflow does not list.
- New issues in a workflow project start on its starting step, with a
  hint naming who they will be handed to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): name built-in steps once in the brief; roomier picker hints (MUL-7420)

Built-in statuses have no stored name, so the handoff brief printed
`todo` todo. Print the key alone when the name adds nothing.

The status picker widens for workflow projects and shows the handoff as
an arrow and name, so step names no longer truncate to one letter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): handoff previews and a single timeline entry per handoff (MUL-7420)

- GET /api/issues/{id}/workflow-handoff?status= says what moving an issue
  would do: who it goes to, which runs of its current agent are still
  active, and the brief the handler receives. Backs the confirmation.
- POST /api/issue-workflows/preview-brief renders a step's brief from an
  unsaved workflow, for the editor's preview.
- Mapping plans list the statuses that stay, so the switch dialog can say
  which issues are untouched.
- A handoff is recorded on the status_changed activity (workflow, handler,
  whether a run started, the brief) instead of a separate assignee row.
- The brief now reads like the one shown in the design: the workflow, the
  current step, its instructions, the statuses, and the commands to hand
  off.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): rebuild the workflow UI to the reviewed design (MUL-7420)

The first cut used generic controls where the design had purpose-built
ones. This brings every surface up to the mockup:

- Settings → Workflows is one page: the workflows (step chain with
  handler avatars, handoff count, projects using it; Default first) and,
  below, the shared status library with each status's workflow usage.
- The workflow editor is a full page instead of a dialog: draggable step
  cards summarising each handoff, and a panel for the selected step —
  swap its status, pick the handler with a segmented control and a
  searchable target, handoff instructions, next/back statuses, a preview
  of the brief the handler receives, duplicate and delete.
- The project Workflow picker lists each workflow's statuses, handoffs and
  projects, links to settings, and always confirms the switch with what
  moves and what stays.
- Moving an issue into a handoff step (status picker, table, board drop)
  asks first: who it goes from and to, a default-on option to stop the
  previous agent's run, and the brief.
- Status pickers name the workflow and project, show each step's handler
  with an avatar or that the assignee stays, and explain themselves.
- Boards: the handler chip in project column heads, hatched columns a
  dragged card cannot enter with the reason, and a drop hint naming who
  the card will go to.
- The timeline records a handoff under its status change, with the brief
  the run received; the issue sidebar shows the workflow it follows.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): word a queued previous run as queued in the handoff confirm

The confirm dialog said the previous agent was "still running (for N
minutes)" even when its task had only been queued. Queued runs now read
as queued, and the checkbox cancels them instead of stopping them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): refuse a run's status change once the issue left its step

A run decides where the issue goes next from the step it was queued for.
When someone else moved the issue while the run worked, applying that
decision undid their move: in the live Grok run, a PM parked NW-1 as
blocked and the still-running agent moved it straight back to code
review.

Tasks now record the issue's status when they are queued
(agent_task_queue.workflow_step, written by the task INSERTs; automatic
retries keep their parent's step), and a run's own status changes move
it along. In a workflow project, an agent status change from a run whose
step no longer matches the issue is refused with 409
workflow_step_moved, naming where the issue is now and who moved it, so
the agent stops instead of retrying.

A handoff away from a squad now also stops the runs made on the squad's
behalf, and stopped runs record who stopped them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): keep every status entry point inside the issue's workflow

The issue context menu listed every catalog status and applied handoff
steps without the confirmation the status picker and board show, so a
right-click could pick a status the workflow refuses or start an agent
unasked. It now offers the workflow's steps and opens the handoff
confirmation through a shared modal.

One-click status actions no longer assume built-in statuses a workflow
may not list: "mark done" lands on the workflow's done step (hidden when
it has none), un-marking a duplicate returns to the workflow's start,
and "mark duplicate" is offered only when the workflow lists cancelled.
The batch toolbar offers a single project's workflow statuses when the
selection sits in one project.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): keep issue wakeups consistent with workflow steps

Three places where project workflows and issue wakeups met:

- A wakeup run is queued when it fires, so it took the issue's status at
  that moment as its workflow step. A wakeup an agent registered then
  bypassed the stale-step refusal: parked by a PM, the issue could be
  moved on by the agent's "check CI, then hand to review" wakeup. It now
  keeps the registering run's step; a member's wakeup still starts from
  the issue's status.
- Retries carried handoff_note only for wakeup runs, so a retried
  workflow handoff lost its brief. Rows with a workflow step keep it.
- Switching or editing a workflow remaps statuses in bulk without the
  close rule, so an issue remapped into a done status kept its wakeups
  and pending wakeup runs. The remap now ends them like any status write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(wakeups): don't also wake the agent a write hands the issue to

A workflow handoff or an assignment already starts the receiving agent's
run. If that agent also subscribed an event wakeup to the issue's status
or assignee, the same write queued a second run for one fact, and
workflows made such writes frequent.

The write now names the agent it hands the issue to in the
transaction-local multica.handed_to_agent (the new agent assignee, a
squad's leader, or a step's handler even when it already owned the
issue), and wakeup capture skips that agent's subscriptions for the
write's issue.* events. Other agents' wakeups, and task, comment and
reaction events, are captured as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): tell agents not to watch workflow issues with wakeups

The handoff brief and the runtime's project workflow section now say
that each step's handler gets a run when the issue enters the step, so
wakeups on a workflow issue are for waiting on time or on something
outside it, not on its status, assignee or runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): refresh project usage after project changes

Co-authored-by: multica-agent <[email protected]>

* feat(workflows): MUL-7420 split columns from per-project handoffs

Workflows now only define a board's columns between a fixed head
(backlog, todo) and tail (blocked, done, cancelled). Handoffs move to
project.workflow_handoffs, so projects can share columns and still hand
off to different people. Default becomes a real, editable row that every
project without a named workflow follows. Adds project handoff, add-column
(project fork or shared) and project brief preview endpoints; same-agent
adjacent columns re-run the agent.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(core): MUL-7420 project handoffs and Default workflow client model

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(views): MUL-7420 column-header handoffs and project workflow menu

Board column headers set the project's handoff for that column; the
project toolbar gets a workflow menu (full flow, switch, templates) and an
add-column action. Views outside a project show Default's columns, with
other statuses reachable through a status filter. Adds the issue flow card,
create-project workflow choice, a columns-only workflow editor and a
lighter status picker.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(views): MUL-7420 wrap create-project workflow label in a menu group

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): MUL-7420 keep workflow structure in settings; no squad handoffs

Projects no longer add columns or create workflows: the add-column
endpoint is removed and creating a workflow is admin-only. Handoffs go
to one agent, a member or the project lead; squads route work themselves,
so a handoff to one is rejected, as is the issue-creator handler.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* refactor(core): MUL-7420 drop the project add-column client

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(views): MUL-7420 simpler handoff picker and workflow editor form

The handoff form is one searchable "Hand to" picker (no handoff, the
project lead, an agent or a member); the next status defaults to the next
column and next/back overrides sit under "More options". The workflow
editor gets labelled name and description fields and shows the fixed
statuses as one start and one end row. Templates move from the project
menu to Settings → Workflows → New, and the project board loses its
add-column action.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* refactor(server): MUL-7420 keep handoffs on the workflow, make backlog and blocked optional

Handoffs move back onto workflow steps: a workflow is the whole pipeline,
and a project only picks one. The project lead stays a relative handler, so
projects can still share a workflow. Handoff edits are admin-only, through
the workflow write or PUT /api/issue-workflows/{id}/handoffs/{status}; the
brief preview moves to the workflow too. Drops the unreleased
project.workflow_handoffs migration.

Todo, done and cancelled are required; backlog and blocked are optional and
keep their fixed places. Without blocked, the brief points agents at the
step's back status.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: Cursor <[email protected]>

* feat(views): MUL-7420 edit handoffs on the workflow, optional backlog and blocked

The workflow editor sets each column's handoff in its side panel, and
Backlog and Blocked switch on and off. The board's column popover and the
flow panel edit the workflow's handoff, say how many projects it reaches,
and are read-only for non-admins. Drops the per-project handoff client
code.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(wakeups): MUL-7420 keep platform rules on writes that hand off nobody

Migration 579 skips an issue.* event for the agent a write hands the issue
to. Its filter compared agent_id with the transaction's handed_to_agent
setting using IS DISTINCT FROM, which is false when both are NULL. Main's
platform rules (child_done) have no agent_id, so every issue.* event that
handed the issue to nobody was dropped for them: a parent leaving backlog
never woke its agent for sub-issues that closed meanwhile
(TestChildDoneHeldWhileParentInBacklog).

Rules without an agent are never the handoff target, so they always
capture. Extends TestHandoffDoesNotAlsoWakeTheHandler with a platform rule
on a handoff and on a plain status change; the latter fails on the old
filter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(views): MUL-7420 three-way handoff choice; quieter move confirm

The handoff form picks one of three directions, as in the mockup: no
handoff, hand to an agent (starts a run), or hand to a member, project lead
included (assignee only). What the step does, where it goes next and the
back status only reach an agent's brief, so they show and save for agent
handoffs alone.

The board's move confirmation keeps the agent's brief collapsed. Create
project shows the workflow picker even when Default is the only workflow,
with a note on where to make more. The hidden-columns panel says a board's
columns come from its workflow, with a link to manage workflows for admins.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(workflows): confirm handoff on project move, per-project handoff copy, two-pane editor (MUL-7420)

- A single issue moved into a workflow project from issue detail confirms
  the handoff of the column it lands on; the write opts in with
  enter_workflow_step. Batch, API and CLI moves stay administrative.
- The handoff preview takes project_id to preview such a move.
- Saving a shared workflow's handoff from a board can keep the change to
  that project: the server copies the workflow for it and switches the
  project in one transaction (copy_for_project_id).
- The column popover says which workflow it edits and who else uses it.
- The workflow editor is a step list with a detail panel for the
  selected step.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* style: gofmt workflow tests

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(views): MUL-7420 show next/back always; edit workflow name and description in place

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* feat(views): MUL-7420 trim copy on the workflows settings page

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix: MUL-7420 keep pre-workflow behavior for workspaces that never adopt workflows

The run step guard now applies only to workflows that hand off, and the
standalone Statuses settings page keeps its original header.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(views): MUL-7420 use a solid placeholder tone on the workflow header

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

* fix(workflows): keep the runtime brief cache-stable; fix project board and batch status gaps (MUL-7420)

- Move the project workflow out of the runtime brief into the per-turn
  prompt so CLAUDE.md stays byte-identical across steps and issues.
- An explicit status filter overrides the project workflow's columns; the
  hidden-columns panel lists statuses outside the workflow.
- Batch status offers only statuses every selected workflow allows; a
  partial batch rolls back, refetches and warns.
- setProjectWorkflow returns void instead of an unparsed body.

Co-authored-by: Cursor <[email protected]>
Co-authored-by: multica-agent <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: multica-agent <[email protected]>
Co-authored-by: Lambda <[email protected]>
Co-authored-by: Cursor <[email protected]>
2026-10-16 16:49:49 +08:00

740 lines
27 KiB
Go

package handler
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"strings"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/issuestatus"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
// Issue status catalog API (MUL-6243).
//
// Reading the catalog is open to any workspace member — every client needs it
// to render a status. Mutating it is owner/admin only: a status is workflow
// configuration shared by the whole workspace, and creating one changes what
// agents can be told to do.
type IssueStatusResponse struct {
ID string `json:"id"`
WorkspaceID string `json:"workspace_id"`
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Category string `json:"category"`
Color string `json:"color"`
Icon string `json:"icon"`
IsSystem bool `json:"is_system"`
Position float64 `json:"position"`
ArchivedAt *string `json:"archived_at"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// terminalIssueStatusKeys resolves the concrete status keys whose categories
// carry terminal behavior. Callers pass the result into indexed status
// predicates instead of resolving the category once per issue row.
func (h *Handler) terminalIssueStatusKeys(ctx context.Context, workspaceID pgtype.UUID) ([]string, error) {
return issuestatus.ExpandCategories(ctx, h.Queries, workspaceID, []string{
issuestatus.CategoryDone,
issuestatus.CategoryClosed,
})
}
func issueStatusToResponse(s db.IssueStatus) IssueStatusResponse {
category := issuestatus.WireCategory(s.Key, s.Category)
return IssueStatusResponse{
ID: uuidToString(s.ID),
WorkspaceID: uuidToString(s.WorkspaceID),
Key: s.Key,
Name: s.Name,
Description: s.Description,
Category: category,
Color: s.Color,
Icon: s.Icon,
IsSystem: s.IsSystem,
Position: s.Position,
ArchivedAt: timestampToPtr(s.ArchivedAt),
CreatedAt: timestampToString(s.CreatedAt),
UpdatedAt: timestampToString(s.UpdatedAt),
}
}
type CreateIssueStatusRequest struct {
// Key is optional; it is derived from Name when omitted. Immutable once
// created, because it is the value stored in issue.status.
Key string `json:"key"`
Name string `json:"name"`
Description string `json:"description"`
Category string `json:"category"`
Color string `json:"color"`
Icon string `json:"icon"`
}
// UpdateIssueStatusRequest deliberately has no Key or Category field. Both are
// immutable: changing a category would silently rewrite the machine semantics
// of every issue already on that status, and changing a key would strand them.
type UpdateIssueStatusRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
Color *string `json:"color"`
Icon *string `json:"icon"`
Position *float64 `json:"position"`
}
// ListIssueStatuses returns the workspace's status catalog in display order.
// Any member may read it.
func (h *Handler) ListIssueStatuses(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
if _, ok := h.requireWorkspaceMember(w, r, workspaceID, "workspace not found"); !ok {
return
}
// Self-heal: a workspace created by a pod that predates this feature has no
// catalog rows. Seeding on read keeps the endpoint correct during a rolling
// deploy without a second backfill pass. Idempotent, so this is a no-op
// once the rows exist.
if err := issuestatus.Ensure(r.Context(), h.Queries, wsUUID); err != nil {
slog.Warn("failed to ensure issue status catalog", append(logger.RequestAttrs(r), "error", err)...)
}
includeArchived := strings.EqualFold(r.URL.Query().Get("include_archived"), "true")
entries, err := h.Queries.ListIssueStatusEntries(r.Context(), db.ListIssueStatusEntriesParams{
WorkspaceID: wsUUID,
IncludeArchived: includeArchived,
})
if err != nil {
slog.Warn("ListIssueStatuses failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to list issue statuses")
return
}
resp := make([]IssueStatusResponse, len(entries))
for i, e := range entries {
resp[i] = issueStatusToResponse(e)
}
writeJSON(w, http.StatusOK, map[string]any{
"statuses": resp,
"categories": issuestatus.Canonical(),
"total": len(resp),
})
}
// CreateIssueStatus adds a custom status to the workspace catalog.
func (h *Handler) CreateIssueStatus(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
if !ok {
return
}
var req CreateIssueStatusRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
name := strings.TrimSpace(req.Name)
if name == "" || len([]rune(name)) > 64 {
writeError(w, http.StatusBadRequest, "name must be 1-64 characters")
return
}
if len([]rune(req.Description)) > 256 {
writeError(w, http.StatusBadRequest, "description must be at most 256 characters")
return
}
category, validCategory := issuestatus.ParseCategory(req.Category)
if !validCategory {
writeError(w, http.StatusBadRequest, "category must be one of: "+strings.Join(issuestatus.Categories(), ", "))
return
}
req.Category = category
if !validIssueStatusIcon(req.Icon) {
writeError(w, http.StatusBadRequest, "invalid status icon")
return
}
color, err := normalizeColor(req.Color)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
// An explicit key wins and is checked here, against the reserved built-in
// names and the storage pattern. Without one the key is DERIVED from the
// display name, which needs the catalog and so happens under the lock in
// createIssueStatusEntry.
var explicitKey string
if strings.TrimSpace(req.Key) != "" {
explicitKey, err = issuestatus.ValidateKey(req.Key)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
}
entry, badRequest, err := h.createIssueStatusEntry(r.Context(), wsUUID, req.Category, db.CreateIssueStatusEntryParams{
WorkspaceID: wsUUID,
Key: explicitKey,
Name: name,
Description: req.Description,
Category: category,
Color: strings.ToLower(color),
Icon: req.Icon,
})
if badRequest != "" {
writeError(w, http.StatusBadRequest, badRequest)
return
}
if err != nil {
if isUniqueViolation(err) {
writeError(w, http.StatusConflict, "a status with this key or name already exists")
return
}
slog.Warn("CreateIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to create issue status")
return
}
h.publishIssueStatusChanged(workspaceID, member, "created")
writeJSON(w, http.StatusCreated, issueStatusToResponse(entry))
}
// createIssueStatusEntry writes one catalog row, deriving arg.Key from the
// display name when it arrives empty.
//
// Derivation READS the catalog to choose a key nothing already owns, so the
// read and the insert have to be a single atomic step: two admins creating a
// Chinese-named Started status at the same instant would otherwise both
// compute `started_2`, and the loser would be told a key they never typed was
// already taken. The EXCLUSIVE catalog lock — the same one archive takes —
// serializes them.
//
// EVERY create takes that lock, including one that supplies its own key.
// Excluding those would leave the race half-closed: an explicit-key insert of
// `started_2` could still land between a derive's catalog read and its
// insert, and the derive — a UI request with no key field to blame — would come
// back 409. The lock is only contended by catalog writes, which are rare admin
// actions, so serializing them costs nothing worth keeping the hole for.
//
// A non-empty second return is a caller error the handler reports as 400,
// distinct from a nil-error success and from an infrastructure failure.
func (h *Handler) createIssueStatusEntry(ctx context.Context, workspaceID pgtype.UUID, publicCategory string, arg db.CreateIssueStatusEntryParams) (db.IssueStatus, string, error) {
tx, err := h.TxStarter.Begin(ctx)
if err != nil {
return db.IssueStatus{}, "", err
}
defer tx.Rollback(ctx)
qtx := h.Queries.WithTx(tx)
if err := qtx.LockIssueStatusCatalog(ctx, workspaceID); err != nil {
return db.IssueStatus{}, "", err
}
entry, badRequest, err := createIssueStatusEntryLocked(ctx, qtx, workspaceID, publicCategory, arg)
if badRequest != "" || err != nil {
return db.IssueStatus{}, badRequest, err
}
if err := tx.Commit(ctx); err != nil {
return db.IssueStatus{}, "", err
}
return entry, "", nil
}
// createIssueStatusEntryLocked is createIssueStatusEntry inside a transaction
// that already holds the exclusive catalog lock.
func createIssueStatusEntryLocked(ctx context.Context, qtx *db.Queries, workspaceID pgtype.UUID, publicCategory string, arg db.CreateIssueStatusEntryParams) (db.IssueStatus, string, error) {
if arg.Key == "" {
// IncludeArchived, because idx_issue_status_workspace_key is NOT a
// partial index: a retired status still owns its key, so reusing it
// would fail on insert instead of producing a second candidate.
entries, err := qtx.ListIssueStatusEntries(ctx, db.ListIssueStatusEntriesParams{
WorkspaceID: workspaceID,
IncludeArchived: true,
})
if err != nil {
return db.IssueStatus{}, "", err
}
taken := make(map[string]bool, len(entries))
for _, e := range entries {
taken[e.Key] = true
}
key, err := issuestatus.DeriveKey(arg.Name, publicCategory, taken)
if err != nil {
return db.IssueStatus{}, err.Error(), nil
}
arg.Key = key
}
entry, err := qtx.CreateIssueStatusEntry(ctx, arg)
if err != nil {
return db.IssueStatus{}, "", err
}
return entry, "", nil
}
// UpdateIssueStatus edits a custom status's presentation. Built-in statuses are
// immutable in v1 — name and color included — so the default workspace looks
// and behaves identically for everyone who never opens this settings page.
func (h *Handler) UpdateIssueStatus(w http.ResponseWriter, r *http.Request) {
entry, wsUUID, member, ok := h.loadIssueStatusForAdmin(w, r)
if !ok {
return
}
var req UpdateIssueStatusRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
if entry.IsSystem {
writeError(w, http.StatusForbidden, "built-in statuses cannot be modified")
return
}
if entry.ArchivedAt.Valid {
writeError(w, http.StatusConflict, "archived statuses cannot be modified")
return
}
var name pgtype.Text
if req.Name != nil {
trimmed := strings.TrimSpace(*req.Name)
if trimmed == "" || len([]rune(trimmed)) > 64 {
writeError(w, http.StatusBadRequest, "name must be 1-64 characters")
return
}
name = pgtype.Text{String: trimmed, Valid: true}
}
var description pgtype.Text
if req.Description != nil {
if len([]rune(*req.Description)) > 256 {
writeError(w, http.StatusBadRequest, "description must be at most 256 characters")
return
}
description = pgtype.Text{String: *req.Description, Valid: true}
}
var color pgtype.Text
if req.Color != nil {
normalized, err := normalizeColor(*req.Color)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
color = pgtype.Text{String: strings.ToLower(normalized), Valid: true}
}
var icon pgtype.Text
if req.Icon != nil {
if !validIssueStatusIcon(*req.Icon) {
writeError(w, http.StatusBadRequest, "invalid status icon")
return
}
icon = pgtype.Text{String: *req.Icon, Valid: true}
}
var position pgtype.Float8
if req.Position != nil {
position = pgtype.Float8{Float64: *req.Position, Valid: true}
}
updated, err := h.Queries.UpdateIssueStatusEntry(r.Context(), db.UpdateIssueStatusEntryParams{
ID: entry.ID,
WorkspaceID: wsUUID,
Name: name,
Description: description,
Color: color,
Icon: icon,
Position: position,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
// The row moved out from under us (archived concurrently, or the
// is_system guard in the statement rejected it).
writeError(w, http.StatusConflict, "status is no longer editable")
return
}
if isUniqueViolation(err) {
writeError(w, http.StatusConflict, "a status with this name already exists")
return
}
slog.Warn("UpdateIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to update issue status")
return
}
h.publishIssueStatusChanged(uuidToString(wsUUID), member, "updated")
writeJSON(w, http.StatusOK, issueStatusToResponse(updated))
}
// These identifiers describe geometry, not workflow semantics. Empty selects
// the category default. Unknown values are rejected on writes, not on reads.
func validIssueStatusIcon(icon string) bool {
switch icon {
case "", "dotted", "circle", "half", "three_quarters", "check", "slash", "cross":
return true
default:
return false
}
}
// ArchiveIssueStatus retires an empty custom status from future assignment.
func (h *Handler) ArchiveIssueStatus(w http.ResponseWriter, r *http.Request) {
entry, wsUUID, member, ok := h.loadIssueStatusForAdmin(w, r)
if !ok {
return
}
if entry.IsSystem {
writeError(w, http.StatusForbidden, "built-in statuses cannot be archived")
return
}
if entry.ArchivedAt.Valid {
writeJSON(w, http.StatusOK, issueStatusToResponse(entry))
return
}
// Count and archive under the EXCLUSIVE catalog lock. Custom-status writers
// re-resolve under its SHARED side, so no assignment can enter between the
// empty check and the archive commit. Migration is a separate user action.
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
slog.Warn("ArchiveIssueStatus begin failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
if err := qtx.LockIssueStatusCatalog(r.Context(), wsUUID); err != nil {
slog.Warn("ArchiveIssueStatus lock failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
count, 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 check issues using status")
return
}
if count > 0 {
writeJSON(w, http.StatusConflict, map[string]any{
"error": fmt.Sprintf("cannot archive status: %d issues still use it; move them to another status first", count),
"code": "issue_status_in_use",
"issue_count": count,
})
return
}
// A status a project workflow lists stays active, or that workflow's
// projects would lose a column. Workflow edits take the same exclusive
// lock, so none can add the status back between this check and the
// archive. (MUL-7420)
workflowNames, err := qtx.ListIssueWorkflowNamesUsingStatusKey(r.Context(), db.ListIssueWorkflowNamesUsingStatusKeyParams{
WorkspaceID: wsUUID,
StatusKey: entry.Key,
})
if err != nil {
slog.Warn("ArchiveIssueStatus workflow check failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to check workflows using status")
return
}
if len(workflowNames) > 0 {
writeJSON(w, http.StatusConflict, map[string]any{
"error": fmt.Sprintf("cannot archive status: workflow %q still uses it; remove it from the workflow first", workflowNames[0]),
"code": "issue_status_in_workflow",
"workflows": workflowNames,
})
return
}
archived, err := qtx.ArchiveIssueStatusEntry(r.Context(), db.ArchiveIssueStatusEntryParams{
ID: entry.ID,
WorkspaceID: wsUUID,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusConflict, "status is no longer archivable")
return
}
slog.Warn("ArchiveIssueStatus failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
if err := qtx.RemoveStatusFromDefaultIssueWorkflow(r.Context(), db.RemoveStatusFromDefaultIssueWorkflowParams{
WorkspaceID: wsUUID,
StatusKey: entry.Key,
}); err != nil {
slog.Warn("ArchiveIssueStatus default workflow update failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
if err := tx.Commit(r.Context()); err != nil {
slog.Warn("ArchiveIssueStatus commit failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to archive issue status")
return
}
// After the commit, never before: an event that announced a change the
// transaction then rolled back would have every other tab re-read the
// catalog and cache the pre-archive row as the new truth.
h.publishIssueStatusChanged(uuidToString(wsUUID), member, "archived")
h.publishIssueWorkflowChanged(uuidToString(wsUUID), member, "updated")
writeJSON(w, http.StatusOK, issueStatusToResponse(archived))
}
// loadIssueStatusForAdmin resolves the {id} path param inside the caller's
// workspace and enforces the owner/admin gate. The member it resolved is
// returned so the write can name its actor on the realtime event.
func (h *Handler) loadIssueStatusForAdmin(w http.ResponseWriter, r *http.Request) (db.IssueStatus, pgtype.UUID, db.Member, bool) {
workspaceID := h.resolveWorkspaceID(r)
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false
}
member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
if !ok {
return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false
}
idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "issue status id")
if !ok {
return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false
}
entry, err := h.Queries.GetIssueStatusEntryByID(r.Context(), db.GetIssueStatusEntryByIDParams{
ID: idUUID,
WorkspaceID: wsUUID,
})
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
writeError(w, http.StatusNotFound, "issue status not found")
return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false
}
slog.Warn("load issue status failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to load issue status")
return db.IssueStatus{}, pgtype.UUID{}, db.Member{}, false
}
return entry, wsUUID, member, true
}
// publishIssueStatusChanged announces that the workspace catalog moved.
//
// One event for every write (see protocol.EventIssueStatusChanged): clients
// re-read the catalog, they do not merge the payload. Nothing about the
// changed row travels here on purpose — a client that merged an entry out of
// an event would have to reconcile it against a concurrent write it cannot
// see, and the catalog is a handful of rows to re-read.
func (h *Handler) publishIssueStatusChanged(workspaceID string, actor db.Member, action string) {
h.publish(protocol.EventIssueStatusChanged, workspaceID, "member", uuidToString(actor.UserID), map[string]any{
"action": action,
})
}
// ReorderIssueStatusesRequest orders a category's active statuses. IncludeSystem
// opts into the complete set; omitted/false preserves the custom-only API used
// by installed clients. Partial sets are rejected in either mode.
type ReorderIssueStatusesRequest struct {
Category string `json:"category"`
IDs []string `json:"ids"`
IncludeSystem bool `json:"include_system"`
}
// ReorderIssueStatuses rewrites the intra-category order of a category's
// statuses, atomically.
//
// Everything happens inside ONE transaction holding the catalog's EXCLUSIVE lock,
// which is the archive path's counterpart. That is not decoration:
//
// - Validating outside the transaction leaves a window. "Validate A and B →
// another request archives B → reorder runs" would write A's new position
// and silently skip B (the UPDATE excludes archived rows), then report 200
// on a half-applied order.
// - The affected-row count is checked against the payload, so any row the
// UPDATE declines to touch fails the whole request instead of committing a
// prefix.
func (h *Handler) ReorderIssueStatuses(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
return
}
member, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin")
if !ok {
return
}
var req ReorderIssueStatusesRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
category, validCategory := issuestatus.ParseCategory(req.Category)
if !validCategory {
writeError(w, http.StatusBadRequest, "category must be one of: "+strings.Join(issuestatus.Categories(), ", "))
return
}
if len(req.IDs) == 0 {
writeError(w, http.StatusBadRequest, "ids must not be empty")
return
}
ids := make([]pgtype.UUID, 0, len(req.IDs))
seen := make(map[string]struct{}, len(req.IDs))
for _, raw := range req.IDs {
if _, duplicate := seen[raw]; duplicate {
writeError(w, http.StatusBadRequest, "duplicate ids")
return
}
seen[raw] = struct{}{}
idUUID, err := util.ParseUUID(raw)
if err != nil {
writeError(w, http.StatusBadRequest, "invalid issue status id")
return
}
ids = append(ids, idUUID)
}
tx, err := h.TxStarter.Begin(r.Context())
if err != nil {
slog.Warn("ReorderIssueStatuses begin failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
return
}
defer tx.Rollback(r.Context())
qtx := h.Queries.WithTx(tx)
// Serialize reorders as well as create/archive, including legacy requests
// that reuse custom rows' existing slots among movable built-ins.
if err := qtx.LockIssueStatusCatalog(r.Context(), wsUUID); err != nil {
slog.Warn("ReorderIssueStatuses lock failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
return
}
// Read the authoritative set under the lock, including built-ins only when
// the caller opts in. No schema or response change is needed.
catalog, err := qtx.ListIssueStatusEntries(r.Context(), db.ListIssueStatusEntriesParams{
WorkspaceID: wsUUID,
IncludeArchived: false,
})
if err != nil {
slog.Warn("ReorderIssueStatuses list failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
return
}
active := make([]db.IssueStatus, 0, len(catalog))
for _, entry := range catalog {
if entry.Category == category && (req.IncludeSystem || !entry.IsSystem) {
active = append(active, entry)
}
}
activeIDs := make(map[string]struct{}, len(active))
for _, entry := range active {
activeIDs[util.UUIDToString(entry.ID)] = struct{}{}
}
for i, raw := range req.IDs {
if _, isActive := activeIDs[raw]; isActive {
continue
}
// Still inside the lock, so this diagnosis cannot go stale. Reported
// per-reason rather than as one opaque conflict, because "you sent a
// built-in" and "someone archived it while you dragged" are different
// problems for the caller.
entry, err := qtx.GetIssueStatusEntryByID(r.Context(), db.GetIssueStatusEntryByIDParams{
ID: ids[i],
WorkspaceID: wsUUID,
})
switch {
case errors.Is(err, pgx.ErrNoRows):
writeError(w, http.StatusNotFound, "issue status not found")
case err != nil:
slog.Warn("load issue status for reorder failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
case entry.IsSystem && !req.IncludeSystem:
writeError(w, http.StatusForbidden, "include_system is required to reorder built-in statuses")
case entry.ArchivedAt.Valid:
writeError(w, http.StatusConflict, "archived statuses cannot be reordered")
case entry.Category != category:
writeError(w, http.StatusBadRequest, "ids must all belong to the requested category")
default:
writeError(w, http.StatusConflict, "issue status catalog changed during reorder")
}
return
}
// Every id is active — so a length mismatch means the payload LEFT ONE OUT.
// Applying it would assign positions from the array index and collide with
// the omitted row, so the whole request is refused.
if len(active) != len(ids) {
writeError(w, http.StatusConflict, "ids must name every active status in the requested reorder scope")
return
}
positions := make([]float64, len(ids))
for i := range ids {
if req.IncludeSystem {
positions[i] = float64(i + 1)
} else {
// Old clients reorder only the custom slots, without moving built-ins
// or colliding with their newly configurable positions.
positions[i] = active[i].Position
}
}
affected, err := qtx.ReorderIssueStatusEntries(r.Context(), db.ReorderIssueStatusEntriesParams{
Ids: ids,
WorkspaceID: wsUUID,
Positions: positions,
IncludeSystem: req.IncludeSystem,
})
if err != nil {
slog.Warn("ReorderIssueStatuses failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
return
}
if affected != int64(len(ids)) {
// Belt and braces behind the lock: if the UPDATE declined a row anyway,
// roll the whole order back rather than commit a prefix.
slog.Warn("ReorderIssueStatuses touched an unexpected row count",
append(logger.RequestAttrs(r), "affected", affected, "expected", len(ids))...)
writeError(w, http.StatusConflict, "issue status catalog changed during reorder")
return
}
entries, err := qtx.ListIssueStatusEntries(r.Context(), db.ListIssueStatusEntriesParams{
WorkspaceID: wsUUID,
IncludeArchived: true,
})
if err != nil {
slog.Warn("list issue statuses after reorder failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to list issue statuses")
return
}
if err := tx.Commit(r.Context()); err != nil {
slog.Warn("ReorderIssueStatuses commit failed", append(logger.RequestAttrs(r), "error", err)...)
writeError(w, http.StatusInternalServerError, "failed to reorder issue statuses")
return
}
h.publishIssueStatusChanged(workspaceID, member, "reordered")
resp := make([]IssueStatusResponse, len(entries))
for i, e := range entries {
resp[i] = issueStatusToResponse(e)
}
writeJSON(w, http.StatusOK, map[string]any{
"statuses": resp,
"categories": issuestatus.Canonical(),
"total": len(resp),
})
}