Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(cli): enable issue ordering via cli (issue reorder, --position, --sort/--direction) (#4110)

Firer519d2aeff073
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 7ff12a8cef..f7462c8622 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -336,10 +336,14 @@ multica issue list --priority urgent --assignee "Agent Name"
multica issue list --assignee-id 5fb87ac7-23b5-4a7a-81fa-ed295a54545d
multica issue list --full-id
multica issue list --limit 20 --output json
+multica issue list --status todo --sort position # board order (the default)
+multica issue list --sort created_at --direction desc # newest first
```
Table output shows a routable issue `KEY` such as `MUL-123`; copy that key into follow-up commands like `issue get`, `issue comment list`, `issue status`, or `--parent`. Add `--full-id` when you need canonical UUIDs. Available filters: `--status`, `--priority`, `--assignee` / `--assignee-id`, `--project`, `--metadata`, `--limit`. Use `--assignee-id <uuid>` for unambiguous filtering when names overlap.
+Results come back in board order (`position`, ascending) by default. Pass `--sort` to change the column (`position`, `title`, `created_at`, `start_date`, `due_date`, `priority`) and `--direction asc|desc` to flip the order. `position` is always ascending (it is the manual drag order), so `--direction` only affects the other columns.
+
Use `--metadata key=value` (repeatable; combined with AND) to filter by per-issue metadata. The value is JSON-parsed: `true`/`false` become bool, numbers become numbers, anything else is a string. Wrap as `'"42"'` to force a string when the value would otherwise sniff as a number:
```bash
@@ -367,8 +371,24 @@ Flags: `--title` (required), `--description`, `--status`, `--priority`, `--assig
```bash
multica issue update <id> --title "New title" --priority urgent
+multica issue update <id> --position 4.5
+```
+
+`--position` sets the raw ordering value within the board column (lower sorts first). For relative moves, `issue reorder` is easier because it works out the value for you.
+
+### Reorder Issue
+
+Move an issue within its current status column. The new ordering value is computed the same way the board's drag-and-drop computes it, so the CLI and UI agree on where the issue lands.
+
+```bash
+multica issue reorder <id> --top # top of its status column
+multica issue reorder <id> --bottom # bottom of its status column
+multica issue reorder <id> --before <other> # directly above another issue in the same column
+multica issue reorder <id> --after <other> # directly below another issue in the same column
```
+Pick exactly one of `--top`, `--bottom`, `--before`, or `--after`. Reorder stays inside the issue's current column, so `--before` / `--after` must name an issue in that same column. To move an issue to a different column, change its status first with `issue status`, then reorder within the new column.
+
### Assign Issue
```bash
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index 2fe93d0e5a..3c80a2d89f 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -148,6 +148,22 @@ var issueStatusCmd = &cobra.Command{
RunE: runIssueStatus,
}
+var issueReorderCmd = &cobra.Command{
+ Use: "reorder <id>",
+ Short: "Move an issue within its status column",
+ Long: "Reposition an issue inside its current status column by computing a new\n" +
+ "ordering position, the same value the board's drag-and-drop sets.\n\n" +
+ "Pick exactly one target:\n" +
+ " --before <id> place it directly above another issue in the same column\n" +
+ " --after <id> place it directly below another issue in the same column\n" +
+ " --top move it to the top of its column\n" +
+ " --bottom move it to the bottom of its column\n\n" +
+ "Reorder stays inside the issue's current column. To move an issue to a\n" +
+ "different column, change its status first with `multica issue status`.",
+ Args: exactArgs(1),
+ RunE: runIssueReorder,
+}
+
// Comment subcommands.
var issueCommentCmd = &cobra.Command{
@@ -273,6 +289,14 @@ var validIssuePriorities = []string{
"urgent", "high", "medium", "low", "none",
}
+// validIssueSortColumns are the sort keys `issue list --sort` accepts. They
+// mirror the server's ListIssues handler. "position" is the default and is
+// always sorted ascending (the board's manual drag order), so --direction is
+// only meaningful for the other columns.
+var validIssueSortColumns = []string{
+ "position", "title", "created_at", "start_date", "due_date", "priority",
+}
+
func validateIssueStatus(status string) error {
return validateIssueEnum("status", status, validIssueStatuses)
}
@@ -299,6 +323,7 @@ func init() {
issueCmd.AddCommand(issueUpdateCmd)
issueCmd.AddCommand(issueAssignCmd)
issueCmd.AddCommand(issueStatusCmd)
+ issueCmd.AddCommand(issueReorderCmd)
issueCmd.AddCommand(issueCommentCmd)
issueCmd.AddCommand(issueSubscriberCmd)
issueCmd.AddCommand(issueRunsCmd)
@@ -329,6 +354,8 @@ func init() {
issueListCmd.Flags().StringSlice("metadata", nil, "Filter by metadata key=value (repeatable; combined with AND). Value is JSON-parsed: 'true'/'false' → bool, numbers → number, otherwise string. Wrap as '\"42\"' to force a string when the value would otherwise sniff as a number.")
issueListCmd.Flags().Int("limit", 50, "Maximum number of issues to return")
issueListCmd.Flags().Int("offset", 0, "Number of issues to skip (for pagination)")
+ issueListCmd.Flags().String("sort", "", "Sort column: position (default, manual board order), title, created_at, start_date, due_date, priority")
+ issueListCmd.Flags().String("direction", "", "Sort direction (asc or desc) for non-position sorts; ignored for position")
// issue get
issueGetCmd.Flags().String("output", "json", "Output format: table or json")
@@ -372,11 +399,19 @@ func init() {
issueUpdateCmd.Flags().String("due-date", "", "New due date (calendar day, YYYY-MM-DD)")
issueUpdateCmd.Flags().String("parent", "", "Parent issue ID (use --parent \"\" to clear)")
issueUpdateCmd.Flags().Int("stage", 0, "Stage ordinal (>=1) for this sub-issue; see `issue create --stage`")
+ issueUpdateCmd.Flags().Float64("position", 0, "Ordering position within the board column (lower sorts first); prefer `issue reorder` for relative moves")
issueUpdateCmd.Flags().String("output", "json", "Output format: table or json")
// issue status
issueStatusCmd.Flags().String("output", "table", "Output format: table or json")
+ // issue reorder
+ issueReorderCmd.Flags().String("before", "", "Place the issue directly above this issue (same column)")
+ issueReorderCmd.Flags().String("after", "", "Place the issue directly below this issue (same column)")
+ issueReorderCmd.Flags().Bool("top", false, "Move the issue to the top of its status column")
+ issueReorderCmd.Flags().Bool("bottom", false, "Move the issue to the bottom of its status column")
+ issueReorderCmd.Flags().String("output", "json", "Output format: table or json")
+
// issue assign
issueAssignCmd.Flags().String("to", "", "Assignee name (member, agent, or squad; fuzzy match)")
issueAssignCmd.Flags().String("to-id", "", "Assignee UUID — member, agent, or squad (mutually exclusive with --to)")
@@ -497,6 +532,26 @@ func runIssueList(cmd *cobra.Command, _ []string) error {
}
params.Set("metadata", filter)
}
+ if v, _ := cmd.Flags().GetString("sort"); v != "" {
+ valid := false
+ for _, c := range validIssueSortColumns {
+ if c == v {
+ valid = true
+ break
+ }
+ }
+ if !valid {
+ return fmt.Errorf("invalid --sort %q; valid values: %s", v, strings.Join(validIssueSortColumns, ", "))
+ }
+ params.Set("sort", v)
+ }
+ if v, _ := cmd.Flags().GetString("direction"); v != "" {
+ d := strings.ToLower(v)
+ if d != "asc" && d != "desc" {
+ return fmt.Errorf("invalid --direction %q; valid values: asc, desc", v)
+ }
+ params.Set("direction", d)
+ }
path := "/api/issues"
if len(params) > 0 {
@@ -1125,6 +1180,10 @@ func runIssueUpdate(cmd *cobra.Command, args []string) error {
}
body["stage"] = stage
}
+ if cmd.Flags().Changed("position") {
+ v, _ := cmd.Flags().GetFloat64("position")
+ body["position"] = v
+ }
if len(body) == 0 {
return fmt.Errorf("no fields to update; use flags like --title, --status, --priority, --assignee, etc.")
@@ -1248,6 +1307,269 @@ func runIssueStatus(cmd *cobra.Command, args []string) error {
return nil
}
+// ---------------------------------------------------------------------------
+// Reorder command
+// ---------------------------------------------------------------------------
+
+// runIssueReorder repositions an issue inside its current status column. The
+// new position is computed client-side by computeReorderPosition, which mirrors
+// the board/list drag-and-drop math (computePosition in
+// packages/views/issues/utils/drag-utils.ts) so the CLI and UI agree on where
+// an issue lands. Only the issue's own position changes; its column membership
+// (status) is left untouched, so cross-column moves still go through
+// `issue status`.
+func runIssueReorder(cmd *cobra.Command, args []string) error {
+ before, _ := cmd.Flags().GetString("before")
+ after, _ := cmd.Flags().GetString("after")
+ top, _ := cmd.Flags().GetBool("top")
+ bottom, _ := cmd.Flags().GetBool("bottom")
+
+ modes := 0
+ for _, set := range []bool{before != "", after != "", top, bottom} {
+ if set {
+ modes++
+ }
+ }
+ if modes != 1 {
+ return fmt.Errorf("exactly one of --before, --after, --top, or --bottom is required")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ wsID := client.WorkspaceID
+ if wsID == "" {
+ wsID, err = requireWorkspaceID(cmd)
+ if err != nil {
+ return err
+ }
+ }
+
+ issueRef, err := resolveIssueRef(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve issue: %w", err)
+ }
+ target, err := fetchIssue(ctx, client, issueRef.ID)
+ if err != nil {
+ return fmt.Errorf("get issue: %w", err)
+ }
+ status := strVal(target, "status")
+ if status == "" {
+ return fmt.Errorf("issue %s has no status, cannot determine its column", issueRef.Display)
+ }
+
+ // Resolve the relative target up front, before any no-op shortcut, so a bad
+ // --before/--after value (typo, self-reference) always errors instead of
+ // being swallowed by the single-issue-column fast path below.
+ relative := before != "" || after != ""
+ var otherRef resolvedID
+ if relative {
+ otherInput := before
+ if after != "" {
+ otherInput = after
+ }
+ otherRef, err = resolveIssueRef(ctx, client, otherInput)
+ if err != nil {
+ return fmt.Errorf("resolve target issue: %w", err)
+ }
+ if otherRef.ID == issueRef.ID {
+ return fmt.Errorf("cannot reorder issue %s relative to itself", issueRef.Display)
+ }
+ }
+
+ // Scope the column to the issue's own project (when it has one) so the
+ // computed position lands relative to the project board the issue lives on,
+ // not a blend of every project's issues in this status.
+ projectID := strVal(target, "project_id")
+ column, err := fetchIssueColumn(ctx, client, wsID, projectID, status)
+ if err != nil {
+ return fmt.Errorf("list %s column: %w", status, err)
+ }
+
+ // Build the column order with the target removed, plus a lookup of every
+ // position in the column (the target's own included, for the no-op check).
+ positions := make(map[string]float64, len(column))
+ ordered := make([]string, 0, len(column))
+ for _, raw := range column {
+ id := strVal(raw, "id")
+ if id == "" {
+ continue
+ }
+ positions[id] = floatVal(raw, "position")
+ if id != issueRef.ID {
+ ordered = append(ordered, id)
+ }
+ }
+ if len(ordered) == 0 {
+ // The active issue is alone in its column. A relative move cannot
+ // succeed here (its target is necessarily in another column), so report
+ // that rather than a misleading "nothing to reorder".
+ if relative {
+ return reorderTargetNotInColumnError(ctx, client, otherRef, issueRef, status)
+ }
+ fmt.Fprintf(os.Stderr, "Issue %s is the only issue in the %s column; nothing to reorder.\n", issueRef.Display, status)
+ return issueReorderOutput(cmd, target)
+ }
+
+ insertIdx := 0
+ switch {
+ case top:
+ insertIdx = 0
+ case bottom:
+ insertIdx = len(ordered)
+ default:
+ idx := indexOfString(ordered, otherRef.ID)
+ if idx == -1 {
+ return reorderTargetNotInColumnError(ctx, client, otherRef, issueRef, status)
+ }
+ if before != "" {
+ insertIdx = idx
+ } else {
+ insertIdx = idx + 1
+ }
+ }
+
+ reordered := make([]string, 0, len(ordered)+1)
+ reordered = append(reordered, ordered[:insertIdx]...)
+ reordered = append(reordered, issueRef.ID)
+ reordered = append(reordered, ordered[insertIdx:]...)
+
+ currentPos := positions[issueRef.ID]
+ newPos := computeReorderPosition(reordered, issueRef.ID, positions, currentPos)
+ if newPos == currentPos {
+ fmt.Fprintf(os.Stderr, "Issue %s is already in that position.\n", issueRef.Display)
+ return issueReorderOutput(cmd, target)
+ }
+
+ var result map[string]any
+ if err := client.PutJSON(ctx, "/api/issues/"+url.PathEscape(issueRef.ID), map[string]any{"position": newPos}, &result); err != nil {
+ return fmt.Errorf("reorder issue: %w", err)
+ }
+ fmt.Fprintf(os.Stderr, "Issue %s reordered.\n", issueDisplayKey(result))
+ return issueReorderOutput(cmd, result)
+}
+
+// issueReorderOutput prints an issue map as a table or JSON, matching the
+// update command's output contract.
+func issueReorderOutput(cmd *cobra.Command, issue map[string]any) error {
+ output, _ := cmd.Flags().GetString("output")
+ if output == "table" {
+ headers := []string{"KEY", "TITLE", "STATUS", "PRIORITY"}
+ rows := [][]string{{
+ issueDisplayKey(issue),
+ strVal(issue, "title"),
+ strVal(issue, "status"),
+ strVal(issue, "priority"),
+ }}
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+ }
+ return cli.PrintJSON(os.Stdout, issue)
+}
+
+// reorderTargetNotInColumnError explains why a --before/--after target could
+// not be used. It fetches the target only to report its actual column in the
+// message, so the common mistake (target lives in a different column) gets a
+// precise, actionable error instead of a bare "not found".
+func reorderTargetNotInColumnError(ctx context.Context, client *cli.APIClient, otherRef, issueRef resolvedID, status string) error {
+ if other, err := fetchIssue(ctx, client, otherRef.ID); err == nil {
+ if otherStatus := strVal(other, "status"); otherStatus != "" && otherStatus != status {
+ return fmt.Errorf("issue %s is in the %q column but %s is in %q; move one with `multica issue status` first, or pick a target in the same column", otherRef.Display, otherStatus, issueRef.Display, status)
+ }
+ }
+ return fmt.Errorf("issue %s was not found in the %q column", otherRef.Display, status)
+}
+
+// fetchIssue retrieves a single issue by canonical ID.
+func fetchIssue(ctx context.Context, client *cli.APIClient, id string) (map[string]any, error) {
+ var issue map[string]any
+ if err := client.GetJSON(ctx, "/api/issues/"+url.PathEscape(id), &issue); err != nil {
+ return nil, err
+ }
+ return issue, nil
+}
+
+// fetchIssueColumn returns every issue in a status column ordered by position
+// ascending, paginating through the list endpoint so columns larger than one
+// page (the server caps a page at 100) still produce a complete, correctly
+// ordered set. A non-empty projectID scopes the column to that project,
+// matching a project board; an empty projectID lists the whole workspace
+// column.
+func fetchIssueColumn(ctx context.Context, client *cli.APIClient, workspaceID, projectID, status string) ([]map[string]any, error) {
+ var all []map[string]any
+ offset := 0
+ for {
+ params := url.Values{}
+ params.Set("workspace_id", workspaceID)
+ params.Set("status", status)
+ if projectID != "" {
+ params.Set("project_id", projectID)
+ }
+ params.Set("sort", "position")
+ params.Set("limit", "100")
+ params.Set("offset", fmt.Sprintf("%d", offset))
+
+ var result map[string]any
+ if err := client.GetJSON(ctx, "/api/issues?"+params.Encode(), &result); err != nil {
+ return nil, err
+ }
+ page, _ := result["issues"].([]any)
+ for _, raw := range page {
+ if m, ok := raw.(map[string]any); ok {
+ all = append(all, m)
+ }
+ }
+ total, _ := result["total"].(float64)
+ offset += len(page)
+ if len(page) == 0 || offset >= int(total) {
+ break
+ }
+ }
+ return all, nil
+}
+
+// computeReorderPosition computes the position that places activeID at its
+// index in ids. It mirrors computePosition in
+// packages/views/issues/utils/drag-utils.ts: the top of a column is one less
+// than the next item, the bottom is one more than the previous, and any
+// interior slot is the midpoint of its neighbours. fallback is returned when
+// activeID is alone in (or absent from) the column, leaving its position
+// unchanged.
+func computeReorderPosition(ids []string, activeID string, positions map[string]float64, fallback float64) float64 {
+ idx := indexOfString(ids, activeID)
+ if idx == -1 || len(ids) == 1 {
+ return fallback
+ }
+ if idx == 0 {
+ return positions[ids[1]] - 1
+ }
+ if idx == len(ids)-1 {
+ return positions[ids[idx-1]] + 1
+ }
+ return (positions[ids[idx-1]] + positions[ids[idx+1]]) / 2
+}
+
+func indexOfString(s []string, target string) int {
+ for i, v := range s {
+ if v == target {
+ return i
+ }
+ }
+ return -1
+}
+
+func floatVal(m map[string]any, key string) float64 {
+ if v, ok := m[key].(float64); ok {
+ return v
+ }
+ return 0
+}
+
// ---------------------------------------------------------------------------
// Comment commands
// ---------------------------------------------------------------------------
diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.go
index 467e07b695..0f3a8cc076 100644
--- a/server/cmd/multica/cmd_issue_test.go
+++ b/server/cmd/multica/cmd_issue_test.go
@@ -2479,3 +2479,519 @@ func TestRunIssueUpdateRejectsInvalidPriorityBeforeRequest(t *testing.T) {
t.Fatalf("expected valid values error, got: %v", err)
}
}
+
+func newIssueUpdateTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "update"}
+ cmd.Flags().String("title", "", "")
+ cmd.Flags().String("description", "", "")
+ cmd.Flags().Bool("description-stdin", false, "")
+ cmd.Flags().String("description-file", "", "")
+ cmd.Flags().String("status", "", "")
+ cmd.Flags().String("priority", "", "")
+ cmd.Flags().String("assignee", "", "")
+ cmd.Flags().String("assignee-id", "", "")
+ cmd.Flags().String("project", "", "")
+ cmd.Flags().String("start-date", "", "")
+ cmd.Flags().String("due-date", "", "")
+ cmd.Flags().String("parent", "", "")
+ cmd.Flags().Float64("position", 0, "")
+ cmd.Flags().String("output", "json", "")
+ return cmd
+}
+
+func newIssueListTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "list"}
+ cmd.Flags().String("output", "table", "")
+ cmd.Flags().Bool("full-id", false, "")
+ cmd.Flags().String("status", "", "")
+ cmd.Flags().String("priority", "", "")
+ cmd.Flags().String("assignee", "", "")
+ cmd.Flags().String("assignee-id", "", "")
+ cmd.Flags().String("project", "", "")
+ cmd.Flags().StringSlice("metadata", nil, "")
+ cmd.Flags().Int("limit", 50, "")
+ cmd.Flags().Int("offset", 0, "")
+ cmd.Flags().String("sort", "", "")
+ cmd.Flags().String("direction", "", "")
+ return cmd
+}
+
+func newIssueReorderTestCmd() *cobra.Command {
+ cmd := &cobra.Command{Use: "reorder"}
+ cmd.Flags().String("before", "", "")
+ cmd.Flags().String("after", "", "")
+ cmd.Flags().Bool("top", false, "")
+ cmd.Flags().Bool("bottom", false, "")
+ cmd.Flags().String("output", "json", "")
+ return cmd
+}
+
+func TestRunIssueUpdateSendsPosition(t *testing.T) {
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": "issue-1", "identifier": "MUL-1", "status": "todo",
+ })
+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]any{
+ "id": "issue-1", "identifier": "MUL-1", "status": "todo", "priority": "none",
+ })
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueUpdateTestCmd()
+ _ = cmd.Flags().Set("position", "7.5")
+ if err := runIssueUpdate(cmd, []string{"MUL-1"}); err != nil {
+ t.Fatalf("runIssueUpdate: %v", err)
+ }
+ if got := body["position"]; got != float64(7.5) {
+ t.Fatalf("position = %#v, want 7.5 in request body", got)
+ }
+}
+
+func TestRunIssueListSendsSortAndDirection(t *testing.T) {
+ var gotQuery url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/issues" {
+ http.NotFound(w, r)
+ return
+ }
+ gotQuery = r.URL.Query()
+ json.NewEncoder(w).Encode(map[string]any{"issues": []any{}, "total": 0})
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueListTestCmd()
+ _ = cmd.Flags().Set("output", "json")
+ _ = cmd.Flags().Set("sort", "created_at")
+ _ = cmd.Flags().Set("direction", "DESC")
+ if err := runIssueList(cmd, nil); err != nil {
+ t.Fatalf("runIssueList: %v", err)
+ }
+ if got := gotQuery.Get("sort"); got != "created_at" {
+ t.Fatalf("sort query = %q, want created_at", got)
+ }
+ if got := gotQuery.Get("direction"); got != "desc" {
+ t.Fatalf("direction query = %q, want desc (lower-cased)", got)
+ }
+}
+
+func TestRunIssueListRejectsInvalidSortAndDirection(t *testing.T) {
+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:0")
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueListTestCmd()
+ _ = cmd.Flags().Set("sort", "nonsense")
+ if err := runIssueList(cmd, nil); err == nil {
+ t.Fatal("runIssueList: expected error for invalid --sort")
+ } else if !strings.Contains(err.Error(), "invalid --sort") {
+ t.Fatalf("error = %q, want it to mention invalid --sort", err)
+ }
+
+ cmd = newIssueListTestCmd()
+ _ = cmd.Flags().Set("direction", "sideways")
+ if err := runIssueList(cmd, nil); err == nil {
+ t.Fatal("runIssueList: expected error for invalid --direction")
+ } else if !strings.Contains(err.Error(), "invalid --direction") {
+ t.Fatalf("error = %q, want it to mention invalid --direction", err)
+ }
+}
+
+func TestComputeReorderPosition(t *testing.T) {
+ positions := map[string]float64{"a": 10, "b": 20, "x": 99}
+ tests := []struct {
+ name string
+ ids []string
+ active string
+ fallback float64
+ want float64
+ }{
+ {"single item keeps position", []string{"x"}, "x", 42, 42},
+ {"absent active keeps position", []string{"a", "b"}, "x", 7, 7},
+ {"top is one below the next", []string{"x", "a", "b"}, "x", 99, 9},
+ {"bottom is one above the prev", []string{"a", "b", "x"}, "x", 99, 21},
+ {"interior is the midpoint", []string{"a", "x", "b"}, "x", 99, 15},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := computeReorderPosition(tc.ids, tc.active, positions, tc.fallback)
+ if got != tc.want {
+ t.Fatalf("computeReorderPosition = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestRunIssueReorderRejectsModeCount(t *testing.T) {
+ t.Run("zero modes", func(t *testing.T) {
+ cmd := newIssueReorderTestCmd()
+ if err := runIssueReorder(cmd, []string{"MUL-1"}); err == nil {
+ t.Fatal("expected error when no mode flag is set")
+ }
+ })
+ t.Run("two modes", func(t *testing.T) {
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("top", "true")
+ _ = cmd.Flags().Set("bottom", "true")
+ if err := runIssueReorder(cmd, []string{"MUL-1"}); err == nil {
+ t.Fatal("expected error when two mode flags are set")
+ }
+ })
+}
+
+// reorderTestServer serves a fixed three-issue "todo" column (positions
+// 1/9/20) plus single-issue lookups by key and id, capturing the position of
+// any PUT so a test can assert where the issue landed.
+func reorderTestServer(t *testing.T, gotPosition *float64) *httptest.Server {
+ t.Helper()
+ issue := func(id, key, status string, pos float64) map[string]any {
+ return map[string]any{"id": id, "identifier": key, "status": status, "position": pos}
+ }
+ a := issue("a-id", "MUL-1", "todo", 1)
+ b := issue("b-id", "MUL-2", "todo", 9)
+ target := issue("t-id", "MUL-9", "todo", 20)
+ c := issue("c-id", "MUL-3", "in_progress", 4)
+ byRef := map[string]map[string]any{
+ "MUL-1": a, "a-id": a,
+ "MUL-2": b, "b-id": b,
+ "MUL-9": target, "t-id": target,
+ "MUL-3": c, "c-id": c,
+ }
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/issues" && r.Method == http.MethodGet {
+ // The column query only ever asks for "todo" in these tests.
+ json.NewEncoder(w).Encode(map[string]any{
+ "issues": []any{a, b, target},
+ "total": 3,
+ })
+ return
+ }
+ ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))
+ found, ok := byRef[ref]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ switch r.Method {
+ case http.MethodGet:
+ json.NewEncoder(w).Encode(found)
+ case http.MethodPut:
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ if p, ok := body["position"].(float64); ok && gotPosition != nil {
+ *gotPosition = p
+ }
+ merged := map[string]any{}
+ for k, v := range found {
+ merged[k] = v
+ }
+ if p, ok := body["position"]; ok {
+ merged["position"] = p
+ }
+ json.NewEncoder(w).Encode(merged)
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+}
+
+func TestRunIssueReorderComputesPosition(t *testing.T) {
+ tests := []struct {
+ name string
+ flag string
+ val string
+ want float64
+ }{
+ {"top of column", "top", "true", 0}, // pos(a) - 1 = 0
+ {"bottom of column", "bottom", "true", 10}, // pos(b) + 1 = 10
+ {"before another issue", "before", "MUL-2", 5}, // midpoint(a=1, b=9)
+ {"after another issue", "after", "MUL-2", 10}, // moves below b (the bottom)
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var gotPosition float64 = -1
+ srv := reorderTestServer(t, &gotPosition)
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set(tc.flag, tc.val)
+ if err := runIssueReorder(cmd, []string{"MUL-9"}); err != nil {
+ t.Fatalf("runIssueReorder: %v", err)
+ }
+ if gotPosition != tc.want {
+ t.Fatalf("PUT position = %v, want %v", gotPosition, tc.want)
+ }
+ })
+ }
+}
+
+func TestRunIssueReorderRejectsCrossColumnTarget(t *testing.T) {
+ srv := reorderTestServer(t, nil)
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("before", "MUL-3") // MUL-3 lives in the in_progress column
+ err := runIssueReorder(cmd, []string{"MUL-9"})
+ if err == nil {
+ t.Fatal("expected error when the --before target is in another column")
+ }
+ if !strings.Contains(err.Error(), "in_progress") || !strings.Contains(err.Error(), "todo") {
+ t.Fatalf("error = %q, want it to name both columns", err)
+ }
+}
+
+func mkIssue(id, key, status string, pos float64) map[string]any {
+ return map[string]any{"id": id, "identifier": key, "status": status, "position": pos}
+}
+
+func TestFetchIssueColumnPaginates(t *testing.T) {
+ all := []map[string]any{
+ mkIssue("i1", "MUL-1", "todo", 1),
+ mkIssue("i2", "MUL-2", "todo", 2),
+ mkIssue("i3", "MUL-3", "todo", 3),
+ }
+ var pageRequests int
+ var sawProject string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/issues" {
+ http.NotFound(w, r)
+ return
+ }
+ pageRequests++
+ sawProject = r.URL.Query().Get("project_id")
+ offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
+ // Force pagination by serving two issues at a time regardless of the
+ // requested limit, so the loop's offset/total termination is exercised.
+ page := []any{}
+ for i := offset; i < offset+2 && i < len(all); i++ {
+ page = append(page, all[i])
+ }
+ json.NewEncoder(w).Encode(map[string]any{"issues": page, "total": len(all)})
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ client, err := newAPIClient(&cobra.Command{Use: "x"})
+ if err != nil {
+ t.Fatalf("newAPIClient: %v", err)
+ }
+ got, err := fetchIssueColumn(context.Background(), client, "ws-1", "proj-1", "todo")
+ if err != nil {
+ t.Fatalf("fetchIssueColumn: %v", err)
+ }
+ if len(got) != 3 {
+ t.Fatalf("got %d issues, want 3 (pagination should accumulate all pages)", len(got))
+ }
+ if pageRequests < 2 {
+ t.Fatalf("page requests = %d, want >= 2 (loop should paginate)", pageRequests)
+ }
+ if sawProject != "proj-1" {
+ t.Fatalf("project_id query = %q, want proj-1 (column should be project-scoped)", sawProject)
+ }
+ for i, want := range []string{"i1", "i2", "i3"} {
+ if got := strVal(got[i], "id"); got != want {
+ t.Fatalf("ordered[%d] = %q, want %q (ascending position order preserved)", i, got, want)
+ }
+ }
+}
+
+func TestRunIssueReorderNoOpSkipsPut(t *testing.T) {
+ // Column order by position: a(0), target(5), b(10). Asking for the target
+ // to go --before b computes (0+10)/2 = 5, which it already holds, so the
+ // command should short-circuit without issuing a PUT.
+ a := mkIssue("a-id", "MUL-1", "todo", 0)
+ b := mkIssue("b-id", "MUL-2", "todo", 10)
+ target := mkIssue("t-id", "MUL-9", "todo", 5)
+ byRef := map[string]map[string]any{
+ "MUL-1": a, "a-id": a,
+ "MUL-2": b, "b-id": b,
+ "MUL-9": target, "t-id": target,
+ }
+ putCalled := false
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/issues" && r.Method == http.MethodGet {
+ json.NewEncoder(w).Encode(map[string]any{"issues": []any{a, target, b}, "total": 3})
+ return
+ }
+ if r.Method == http.MethodPut {
+ putCalled = true
+ http.NotFound(w, r)
+ return
+ }
+ ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))
+ if found, ok := byRef[ref]; ok {
+ json.NewEncoder(w).Encode(found)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("before", "MUL-2")
+ if err := runIssueReorder(cmd, []string{"MUL-9"}); err != nil {
+ t.Fatalf("runIssueReorder: %v", err)
+ }
+ if putCalled {
+ t.Fatal("expected no PUT when the issue is already in the requested position")
+ }
+}
+
+func TestRunIssueReorderSingleItemColumnValidatesTarget(t *testing.T) {
+ // The "todo" column holds only the issue being moved; MUL-3 lives in a
+ // different column. A relative move must still validate its target rather
+ // than reporting a successful no-op (regression guard for the single-item
+ // fast path running before target resolution).
+ target := mkIssue("t-id", "MUL-9", "todo", 5)
+ other := mkIssue("c-id", "MUL-3", "in_progress", 2)
+ byRef := map[string]map[string]any{
+ "MUL-9": target, "t-id": target,
+ "MUL-3": other, "c-id": other,
+ }
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/issues" && r.Method == http.MethodGet {
+ json.NewEncoder(w).Encode(map[string]any{"issues": []any{target}, "total": 1})
+ return
+ }
+ ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))
+ if found, ok := byRef[ref]; ok {
+ json.NewEncoder(w).Encode(found)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ t.Run("cross-column target errors", func(t *testing.T) {
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("after", "MUL-3")
+ err := runIssueReorder(cmd, []string{"MUL-9"})
+ if err == nil {
+ t.Fatal("expected an error, not a silent no-op")
+ }
+ if !strings.Contains(err.Error(), "in_progress") {
+ t.Fatalf("error = %q, want it to name the target's column", err)
+ }
+ })
+
+ t.Run("self target errors", func(t *testing.T) {
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("before", "MUL-9")
+ err := runIssueReorder(cmd, []string{"MUL-9"})
+ if err == nil {
+ t.Fatal("expected an error when targeting itself")
+ }
+ if !strings.Contains(err.Error(), "itself") {
+ t.Fatalf("error = %q, want it to mention self-reference", err)
+ }
+ })
+}
+
+func TestRunIssueReorderOnlyIssueInColumnIsNoOp(t *testing.T) {
+ // A --top/--bottom move on a single-issue column has nowhere to go, so it
+ // short-circuits without a PUT instead of rewriting the position.
+ target := mkIssue("t-id", "MUL-9", "todo", 5)
+ putCalled := false
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/issues" && r.Method == http.MethodGet {
+ json.NewEncoder(w).Encode(map[string]any{"issues": []any{target}, "total": 1})
+ return
+ }
+ if r.Method == http.MethodPut {
+ putCalled = true
+ http.NotFound(w, r)
+ return
+ }
+ ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))
+ if ref == "MUL-9" || ref == "t-id" {
+ json.NewEncoder(w).Encode(target)
+ return
+ }
+ http.NotFound(w, r)
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueReorderTestCmd()
+ _ = cmd.Flags().Set("top", "true")
+ if err := runIssueReorder(cmd, []string{"MUL-9"}); err != nil {
+ t.Fatalf("runIssueReorder: %v", err)
+ }
+ if putCalled {
+ t.Fatal("expected no PUT when the issue is alone in its column")
+ }
+}
+
+func TestRunIssueUpdateOmitsPositionWhenUnset(t *testing.T) {
+ // position 0 is a real, meaningful value, so an update that does not pass
+ // --position must not send "position" at all (Flags().Changed guard).
+ var body map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/MUL-1":
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "status": "todo"})
+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/issue-1":
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode body: %v", err)
+ }
+ json.NewEncoder(w).Encode(map[string]any{"id": "issue-1", "identifier": "MUL-1", "title": "Renamed"})
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ defer srv.Close()
+
+ t.Setenv("MULTICA_SERVER_URL", srv.URL)
+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")
+ t.Setenv("MULTICA_TOKEN", "test-token")
+
+ cmd := newIssueUpdateTestCmd()
+ _ = cmd.Flags().Set("title", "Renamed")
+ if err := runIssueUpdate(cmd, []string{"MUL-1"}); err != nil {
+ t.Fatalf("runIssueUpdate: %v", err)
+ }
+ if _, present := body["position"]; present {
+ t.Fatalf("position must be absent from the body when --position is not passed, got %#v", body["position"])
+ }
+}