Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): fail safely when pagination counts are unavailable (#8201)
Multica Eve9d0cab0eac06
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex b4e2cd4a2c..5bccb6a93d 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -510,6 +510,8 @@ multica issue list --output json --resolve-properties # property names beside tTable 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`, `--property`, plus `--limit` and `--offset` for paging. Use `--assignee-id <uuid>` for unambiguous filtering when names overlap.+If the server cannot count the matching issues, the list request fails with `failed to count issues` instead of returning the page length as a fabricated total. Successful response fields are unchanged. This trades availability of a partial page for an explicit failure that callers can retry.+`--fields` (JSON output only) whitelists which top-level issue keys come back — pass a comma-separated list such as `--fields=id,title,status,priority`. Omit it for the full issue object, unchanged from before this flag existed. Filtering happens client-side after the CLI fetches the full response, so this shrinks CLI output size and agent context cost — not network transfer or server-side work. Field names are the real API keys, not table-display labels — assignee is `assignee_type`/`assignee_id` rather than a single `assignee` field. An unknown name is rejected up front with the valid list rather than silently dropped. Has no effect on `--output table`.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`, or `property:<name-or-id>` for a custom property — select properties order by option order, and issues without the property sort last) and `--direction asc|desc` to flip the order. `position` is always ascending (it is the manual drag order), so `--direction` is rejected when `--sort` is `position` or omitted — use it only with `title`, `created_at`, `start_date`, `due_date`, `priority`, or a `property:` sort.@@ -578,6 +580,8 @@ multica issue reorder <id> --after <other> # directly below another issue inPick 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.+Reorder reads the project-scoped column before computing the new position. With older servers that omit the total or substitute the page length after a failed count, it continues to an empty page instead of trusting that count. This may cost one extra request. A failed page request, malformed issue, or repeated issue aborts the operation before a position is written. These checks do not provide a consistent snapshot across concurrent edits.+### Assign Issue```bashdiff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex 085167ee1e..1d2eb2b624 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -1923,6 +1923,7 @@ func fetchIssue(ctx context.Context, client *cli.APIClient, id string) (map[stri// workspace column.func fetchIssueColumn(ctx context.Context, client *cli.APIClient, workspaceID, projectID, status string) ([]map[string]any, error) {var all []map[string]any+ seen := make(map[string]struct{})offset := 0for {params := url.Values{}@@ -1939,15 +1940,31 @@ func fetchIssueColumn(ctx context.Context, client *cli.APIClient, workspaceID, pif err := client.GetJSON(ctx, "/api/issues?"+params.Encode(), &result); err != nil {return nil, err}- page, _ := result["issues"].([]any)+ page, ok := result["issues"].([]any)+ if !ok {+ return nil, fmt.Errorf("invalid issue column response: expected an issues array")+ }for _, raw := range page {- if m, ok := raw.(map[string]any); ok {- all = append(all, m)+ m, ok := raw.(map[string]any)+ if !ok || strVal(m, "id") == "" {+ return nil, fmt.Errorf("invalid issue in column response")+ }+ id := strVal(m, "id")+ if _, exists := seen[id]; exists {+ return nil, fmt.Errorf("issue column returned duplicate issue %s; retry the reorder", id)}+ seen[id] = struct{}{}+ all = append(all, m)}- total, _ := result["total"].(float64)+ total, totalOK := result["total"].(float64)offset += len(page)- if len(page) == 0 || offset >= int(total) {+ // Older servers substitute the page length when COUNT fails. Such a+ // total cannot prove the column is complete. Without a usable count,+ // read through the empty page, including when the server uses smaller+ // pages; a short page does not establish its applied limit. Duplicate+ // IDs above reject a repeated page before any position is written.+ totalTrusted := totalOK && total > float64(len(page))+ if len(page) == 0 || (totalTrusted && float64(offset) >= total) {break}}diff --git a/server/cmd/multica/cmd_issue_reorder_pagination_test.go b/server/cmd/multica/cmd_issue_reorder_pagination_test.gonew file mode 100644index 0000000000..c2ae015390--- /dev/null+++ b/server/cmd/multica/cmd_issue_reorder_pagination_test.go@@ -0,0 +1,100 @@+package main++import (+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"+)++// Reorder may probe beyond a genuine single-page total because legacy servers+// use that same value when COUNT fails. Fixtures must honor offset as the API does.+func writeReorderColumnPage(w http.ResponseWriter, r *http.Request, all []any) {+ offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))+ page := all[min(offset, len(all)):min(offset+100, len(all))]+ _ = json.NewEncoder(w).Encode(map[string]any{"issues": page, "total": len(all)})+}++func TestRunIssueReorderPaginationIntegrity(t *testing.T) {+ for _, mode := range []string{"healthy", "failed_count", "missing_total", "smaller_pages", "next_page_error", "duplicate_page", "malformed_page", "missing_page"} {+ t.Run(mode, func(t *testing.T) {+ t.Chdir(t.TempDir())+ all := make([]map[string]any, 145)+ for i := range all {+ all[i] = mkIssue(fmt.Sprintf("11111111-1111-4111-8111-%012d", i+1), fmt.Sprintf("MUL-%d", i+1), "todo", float64(i))+ all[i]["project_id"] = "project-1"+ }+ target := all[0]+ position, requests, writes := -1.0, 0, 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues":+ requests+++ q := r.URL.Query()+ for key, want := range map[string]string{"workspace_id": "ws-1", "project_id": "project-1", "status": "todo", "sort": "position", "limit": "100"} {+ if q.Get(key) != want {+ t.Errorf("%s=%q, want %q", key, q.Get(key), want)+ }+ }+ offset, _ := strconv.Atoi(q.Get("offset"))+ if mode == "next_page_error" && offset > 0 {+ http.Error(w, "failed to count issues", http.StatusInternalServerError)+ return+ }+ if mode == "duplicate_page" {+ offset = 0+ }+ pageSize := 100+ if mode == "smaller_pages" {+ pageSize = 20+ }+ page := all[min(offset, len(all)):min(offset+pageSize, len(all))]+ body := map[string]any{"issues": page, "total": len(all)}+ switch mode {+ case "failed_count", "smaller_pages":+ body["total"] = len(page)+ case "missing_total":+ delete(body, "total")+ case "malformed_page":+ body["issues"] = []any{nil}+ case "missing_page":+ delete(body, "issues")+ }+ _ = json.NewEncoder(w).Encode(body)+ case r.Method == http.MethodGet && r.URL.Path == "/api/issues/"+strVal(target, "id"):+ _ = json.NewEncoder(w).Encode(target)+ case r.Method == http.MethodPut && r.URL.Path == "/api/issues/"+strVal(target, "id"):+ writes+++ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ position = floatVal(body, "position")+ _ = json.NewEncoder(w).Encode(target)+ 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 := newIssueReorderTestCmd()+ _ = cmd.Flags().Set("bottom", "true")+ _, err := captureStdout(t, func() error { return runIssueReorder(cmd, []string{strVal(target, "id")}) })+ switch mode {+ case "next_page_error", "duplicate_page", "malformed_page", "missing_page":+ if err == nil || writes != 0 {+ t.Fatalf("invalid column must prevent writes: err=%v, writes=%d", err, writes)+ }+ default:+ if err != nil {+ t.Fatal(err)+ }+ if position != 145 || writes != 1 {+ t.Fatalf("bottom position=%v, writes=%d, pages=%d; want one write at 145", position, writes, requests)+ }+ }+ })+ }+}diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 11153f2fee..447c6fe884 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -3649,10 +3649,7 @@ func reorderTestServer(t *testing.T, gotPosition *float64) *httptest.Server {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,- })+ writeReorderColumnPage(w, r, []any{a, b, target})return}ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))@@ -3843,7 +3840,7 @@ func TestRunIssueReorderNoOpSkipsPut(t *testing.T) {putCalled := falsesrv := 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})+ writeReorderColumnPage(w, r, []any{a, target, b})return}if r.Method == http.MethodPut {@@ -3887,7 +3884,7 @@ func TestRunIssueReorderSingleItemColumnValidatesTarget(t *testing.T) {}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})+ writeReorderColumnPage(w, r, []any{target})return}ref, _ := url.PathUnescape(strings.TrimPrefix(r.URL.Path, "/api/issues/"))@@ -3935,7 +3932,7 @@ func TestRunIssueReorderOnlyIssueInColumnIsNoOp(t *testing.T) {putCalled := falsesrv := 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})+ writeReorderColumnPage(w, r, []any{target})return}if r.Method == http.MethodPut {diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 3b5161162b..b1ce51e657 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -1570,7 +1570,9 @@ LIMIT %s OFFSET %s`, whereSql, orderBy, limitRef, offsetRef)countArgs := args[:len(args)-2]var total int64if err := h.DB.QueryRow(ctx, countQuery, countArgs...).Scan(&total); err != nil {- total = int64(len(issues))+ slog.Warn("ListIssues count failed", "error", err)+ writeError(w, http.StatusInternalServerError, "failed to count issues")+ return}prefix := h.getIssuePrefix(ctx, wsUUID)diff --git a/server/internal/handler/issue_count_failure_test.go b/server/internal/handler/issue_count_failure_test.gonew file mode 100644index 0000000000..4f266a0b9f--- /dev/null+++ b/server/internal/handler/issue_count_failure_test.go@@ -0,0 +1,64 @@+package handler++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/testutil"+)++type issueCountFailureDB struct {+ dbExecutor+ failures int+}++func (db *issueCountFailureDB) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {+ if strings.HasPrefix(sql, "SELECT COUNT(*) FROM issue i WHERE ") {+ db.failures+++ return issueCountFailureRow{}+ }+ return db.dbExecutor.QueryRow(ctx, sql, args...)+}++type issueCountFailureRow struct{}++func (issueCountFailureRow) Scan(...any) error {+ return errors.New("injected COUNT failure: private SQL details")+}++func TestListIssuesCountFailureDoesNotReturnPartialSuccess(t *testing.T) {+ projectID := dbfx.Project(t, "Count failure")+ for i := 0; i < 3; i++ {+ dbfx.Issue(t, fmt.Sprintf("Counted issue %d", i), testutil.Cols{"project_id": projectID})+ }+ for _, offset := range []int{0, 2, 100} {+ t.Run(fmt.Sprintf("offset_%d", offset), func(t *testing.T) {+ path := fmt.Sprintf("/api/issues?workspace_id=%s&project_id=%s&limit=2&offset=%d", testWorkspaceID, projectID, offset)+ // Prove that rows and the count are normally available for this query.+ var healthy struct {+ Issues []IssueResponse `json:"issues"`+ Total int `json:"total"`+ }+ testutil.Call(t, testHandler.ListIssues, newRequest("GET", path, nil)).Want(http.StatusOK).JSON(&healthy)+ if healthy.Total != 3 || len(healthy.Issues) != max(0, min(2, 3-offset)) {+ t.Fatalf("unexpected healthy page: %+v", healthy)+ }++ h := *testHandler+ failingDB := &issueCountFailureDB{dbExecutor: h.DB}+ h.DB = failingDB+ body := testutil.Call(t, h.ListIssues, newRequest("GET", path, nil)).Want(http.StatusInternalServerError).Map()+ if failingDB.failures != 1 {+ t.Fatalf("injected %d count failures, want 1", failingDB.failures)+ }+ if len(body) != 1 || body["error"] != "failed to count issues" {+ t.Fatalf("failure must expose only a public error, not issues, total, or SQL: %v", body)+ }+ })+ }+}diff --git a/server/internal/service/builtin_skills/multica-platform/references/issues.md b/server/internal/service/builtin_skills/multica-platform/references/issues.mdindex 2f42071b8c..790e2fe6d8 100644--- a/server/internal/service/builtin_skills/multica-platform/references/issues.md+++ b/server/internal/service/builtin_skills/multica-platform/references/issues.md@@ -124,6 +124,22 @@ not observe a routable issue key in the PR title/body/branch — or the only matwas a bare body mention, which links as `reference_only` and is hidden from thislist (see the reference-only rule above).+## Listing and ordering issues++`issue list` reads one page at a time, with a server maximum of 100 issues.+Advance `--offset` by the number of issues actually returned. If the server+cannot count matching issues, it returns `failed to count issues` as an error;+do not treat that failure as an empty or complete list. Older servers can+substitute the page length for a failed count, so that value alone is not proof+that all matching issues have been read.++`issue reorder` reads the issue's project-scoped status column before writing+its new position. When a legacy total is unavailable or no larger than its+page, it reads through an empty page. A failed request, malformed page, or+duplicate issue stops the operation before any position write. This protects+against truncated or repeated pages, but does not promise a snapshot across+concurrent edits. There is no CLI bulk-export or `--all` mode.+## Custom properties: typed workflow stateWorkspaces may define custom issue properties (Severity, Environment, QA