Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(cli): add --project filter to issue search (#10088)
AstralSolipsism8abb2b4afa4e
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 0d2a08b3c1..5799b6e23d 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -942,12 +942,13 @@ multica project delete <id>### Associating Issues with ProjectsUse the `--project` flag on `issue create` / `issue update` to attach an issue to a-project, or on `issue list` to filter issues by project:+project, or on `issue list` / `issue search` to filter issues by project:```bashmultica issue create --title "Login bug" --project <project-id>multica issue update <issue-id> --project <project-id>multica issue list --project <project-id>+multica issue search "Login" --project <project-id>```## Setupdiff --git a/apps/docs/content/docs/cli.fr.mdx b/apps/docs/content/docs/cli.fr.mdxindex df2bc00d85..7df45ee433 100644--- a/apps/docs/content/docs/cli.fr.mdx+++ b/apps/docs/content/docs/cli.fr.mdx@@ -373,7 +373,7 @@ Les tableaux ci-dessous couvrent toutes les commandes de premier niveau actuelle| | `assign <id>` | Assigner ou désassigner | `--to` (correspondance approximative sur le nom parmi les membres, les agents et les squads), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | Changer le statut | `--no-start`, `--duplicate-of` || | `reorder <id>` | Déplacer au sein d'une colonne | |-| | `search <query>` | Rechercher des tâches | `--limit`, `--include-closed` |+| | `search <query>` | Rechercher des tâches | `--limit`, `--include-closed`, `--project` || | `children <id>` | Lister les sous-tâches regroupées par étape | || | `pull-requests <id>` | Lister les PR associées | || | `comment list/add/update/delete/resolve/unresolve` | Gérer les commentaires | `add` : `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment` ; `update` : `--expected-revision` (obligatoire), `--content` / `--content-stdin` / `--content-file` ; `list` : `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` |diff --git a/apps/docs/content/docs/cli.ja.mdx b/apps/docs/content/docs/cli.ja.mdxindex c8dda9ac8a..0225dd36dc 100644--- a/apps/docs/content/docs/cli.ja.mdx+++ b/apps/docs/content/docs/cli.ja.mdx@@ -365,7 +365,7 @@ CLI の設定ファイルには、あなたとして Multica にアクセスで| | `assign <id>` | 割り当てまたは割り当て解除 | `--to`(メンバー、エージェント、スクワッドを名前であいまいマッチ)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | ステータスを変更 | `--no-start`、`--duplicate-of` || | `reorder <id>` | カラム内で移動 | |-| | `search <query>` | タスクを検索 | `--limit`、`--include-closed` |+| | `search <query>` | タスクを検索 | `--limit`、`--include-closed`、`--project` || | `children <id>` | サブタスクをステージごとに一覧 | || | `pull-requests <id>` | 関連付けられた PR を一覧 | || | `comment list/add/update/delete/resolve/unresolve` | コメントを管理 | `add`: `--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`: `--expected-revision`(必須)、`--content` / `--content-stdin` / `--content-file`;`list`: `--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` |diff --git a/apps/docs/content/docs/cli.ko.mdx b/apps/docs/content/docs/cli.ko.mdxindex 337c8e9283..6c7c22f7cd 100644--- a/apps/docs/content/docs/cli.ko.mdx+++ b/apps/docs/content/docs/cli.ko.mdx@@ -365,7 +365,7 @@ CLI 설정 파일에는 사용자를 대신해 Multica에 접근할 수 있는 t| | `assign <id>` | 할당 또는 할당 해제 | `--to`(이름으로 멤버, 에이전트, 스쿼드 fuzzy match), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | 상태 변경 | `--no-start`, `--duplicate-of` || | `reorder <id>` | 열 안에서 이동 | |-| | `search <query>` | 태스크 검색 | `--limit`, `--include-closed` |+| | `search <query>` | 태스크 검색 | `--limit`, `--include-closed`, `--project` || | `children <id>` | 단계별로 묶은 하위 태스크 목록 | || | `pull-requests <id>` | 연결된 PR 목록 | || | `comment list/add/update/delete/resolve/unresolve` | 댓글 관리 | `add`: `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment`. `update`: `--expected-revision`(필수), `--content` / `--content-stdin` / `--content-file`. `list`: `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` |diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 893c3e3471..07696b4280 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -395,7 +395,7 @@ Migration from CSV parsing: replace `--attachment a,b` with `--attachment a --at| | `assign <id>` | Assign or unassign | `--to` (fuzzy name match against members, agents, and squads), `--to-id`, `--unassign`, `--no-start` || | `status <id> <status>` | Change status | `--no-start`, `--duplicate-of` || | `reorder <id>` | Move within a column | |-| | `search <query>` | Search issues | `--limit`, `--include-closed` |+| | `search <query>` | Search issues | `--limit`, `--include-closed`, `--project` || | `children <id>` | List sub-issues grouped by stage | || | `pull-requests <id>` | List linked PRs | || | `comment list/add/update/delete/resolve/unresolve` | Manage comments | `add`: `--content` / `--content-stdin` / `--content-file`, `--parent`, `--attachment`; `update`: `--expected-revision` (required), `--content` / `--content-stdin` / `--content-file`; `list`: `--since`, `--thread`, `--tail`, `--recent`, `--roots-only`, `--summary`, `--compact`, `--full` |diff --git a/apps/docs/content/docs/cli.zh-Hant.mdx b/apps/docs/content/docs/cli.zh-Hant.mdxindex 68cec68011..9d8f2dfdbb 100644--- a/apps/docs/content/docs/cli.zh-Hant.mdx+++ b/apps/docs/content/docs/cli.zh-Hant.mdx@@ -369,7 +369,7 @@ CLI 配置檔案包含可代表你訪問 Multica 的令牌。不要提交到倉| | `assign <id>` | 指派或取消指派 | `--to`(名稱模糊匹配成員、AI 代理或小隊)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | 修改狀態 | `--no-start`、`--duplicate-of` || | `reorder <id>` | 在列內移動 | |-| | `search <query>` | 搜尋任務 | `--limit`、`--include-closed` |+| | `search <query>` | 搜尋任務 | `--limit`、`--include-closed`、`--project` || | `children <id>` | 按階段分組列出子任務 | || | `pull-requests <id>` | 列出關聯的 PR | || | `comment list/add/update/delete/resolve/unresolve` | 管理評論 | `add`:`--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`:`--expected-revision`(必填)、`--content` / `--content-stdin` / `--content-file`;`list`:`--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` |diff --git a/apps/docs/content/docs/cli.zh.mdx b/apps/docs/content/docs/cli.zh.mdxindex 8e9b8875b0..c9bd57a3d7 100644--- a/apps/docs/content/docs/cli.zh.mdx+++ b/apps/docs/content/docs/cli.zh.mdx@@ -372,7 +372,7 @@ CLI 配置文件包含可代表你访问 Multica 的令牌。不要提交到仓| | `assign <id>` | 指派或取消指派 | `--to`(名称模糊匹配成员、智能体或小队)、`--to-id`、`--unassign`、`--no-start` || | `status <id> <status>` | 修改状态 | `--no-start`、`--duplicate-of` || | `reorder <id>` | 在列内移动 | |-| | `search <query>` | 搜索任务 | `--limit`、`--include-closed` |+| | `search <query>` | 搜索任务 | `--limit`、`--include-closed`、`--project` || | `children <id>` | 按阶段分组列出子任务 | || | `pull-requests <id>` | 列出关联的 PR | || | `comment list/add/update/delete/resolve/unresolve` | 管理评论 | `add`:`--content` / `--content-stdin` / `--content-file`、`--parent`、`--attachment`;`update`:`--expected-revision`(必填)、`--content` / `--content-stdin` / `--content-file`;`list`:`--since`、`--thread`、`--tail`、`--recent`、`--roots-only`、`--summary`、`--compact`、`--full` |diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.goindex e85fd5b305..60a5a51487 100644--- a/server/cmd/multica/cmd_issue.go+++ b/server/cmd/multica/cmd_issue.go@@ -783,6 +783,7 @@ func init() {// issue searchissueSearchCmd.Flags().Int("limit", 20, "Maximum number of results to return")issueSearchCmd.Flags().Bool("include-closed", false, "Include done and cancelled issues")+ issueSearchCmd.Flags().String("project", "", "Filter by project ID")issueSearchCmd.Flags().String("output", "table", "Output format: table or json")// issue subscriber list@@ -3225,6 +3226,18 @@ func runIssueSearch(cmd *cobra.Command, args []string) error {if v, _ := cmd.Flags().GetBool("include-closed"); v {params.Set("include_closed", "true")}+ if projectInput, _ := cmd.Flags().GetString("project"); projectInput != "" {+ if client.WorkspaceID == "" {+ if _, err := requireWorkspaceID(cmd); err != nil {+ return err+ }+ }+ project, err := resolveProjectID(ctx, client, projectInput)+ if err != nil {+ return err+ }+ params.Set("project_id", project.ID)+ }path := "/api/issues/search?" + params.Encode()diff --git a/server/cmd/multica/cmd_issue_test.go b/server/cmd/multica/cmd_issue_test.goindex 213f1c659a..985f197933 100644--- a/server/cmd/multica/cmd_issue_test.go+++ b/server/cmd/multica/cmd_issue_test.go@@ -6045,3 +6045,127 @@ func TestRunIssueCommentDeleteKeepsReplies(t *testing.T) {})}}++func newIssueSearchTestCmd() *cobra.Command {+ cmd := &cobra.Command{Use: "search"}+ cmd.Flags().Int("limit", 20, "")+ cmd.Flags().Bool("include-closed", false, "")+ cmd.Flags().String("project", "", "")+ cmd.Flags().String("output", "json", "")+ return cmd+}++func TestRunIssueSearchSendsProjectID(t *testing.T) {+ const projectID = "11111111-2222-3333-4444-555555555555"+ var gotQuery url.Values+ var requestPaths []string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requestPaths = append(requestPaths, r.URL.Path)+ gotQuery = r.URL.Query()+ w.Header().Set("Content-Type", "application/json")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "issues": []any{},+ })+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ cmd := newIssueSearchTestCmd()+ _ = cmd.Flags().Set("project", projectID)+ _, err := captureStdout(t, func() error {+ return runIssueSearch(cmd, []string{"auth bug"})+ })+ if err != nil {+ t.Fatalf("runIssueSearch: %v", err)+ }+ if want := []string{"/api/issues/search"}; !slices.Equal(requestPaths, want) {+ t.Fatalf("requests = %v, want %v", requestPaths, want)+ }+ if got := gotQuery.Get("q"); got != "auth bug" {+ t.Errorf("q = %q, want %q", got, "auth bug")+ }+ if got := gotQuery.Get("project_id"); got != projectID {+ t.Errorf("project_id = %q, want %q", got, projectID)+ }+}++func TestRunIssueSearchResolvesProjectPrefix(t *testing.T) {+ const fullProjectID = "11111111-2222-3333-4444-555555555555"+ var gotSearchProjectID string+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ switch r.URL.Path {+ case "/api/projects":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "projects": []map[string]any{+ {"id": fullProjectID, "title": "Core Platform", "status": "in_progress"},+ },+ })+ case "/api/issues/search":+ gotSearchProjectID = r.URL.Query().Get("project_id")+ _ = json.NewEncoder(w).Encode(map[string]any{+ "issues": []any{},+ })+ default:+ t.Fatalf("unexpected request path: %s", r.URL.Path)+ }+ }))+ defer srv.Close()++ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "mat_test-token")++ cmd := newIssueSearchTestCmd()+ _ = cmd.Flags().Set("project", "11111111")+ _, err := captureStdout(t, func() error {+ return runIssueSearch(cmd, []string{"deployment"})+ })+ if err != nil {+ t.Fatalf("runIssueSearch: %v", err)+ }+ if gotSearchProjectID != fullProjectID {+ t.Fatalf("project_id = %q, want %q", gotSearchProjectID, fullProjectID)+ }+}++func TestRunIssueSearchProjectFilterErrors(t *testing.T) {+ t.Setenv("MULTICA_SERVER_URL", "http://127.0.0.1:1")+ t.Setenv("MULTICA_TOKEN", "mat_test-token")+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")++ cmd := newIssueSearchTestCmd()+ _ = cmd.Flags().Set("project", "xyz")+ err := runIssueSearch(cmd, []string{"deployment"})+ if err == nil {+ t.Fatal("expected error for malformed project prefix")+ }+ if count := strings.Count(err.Error(), "resolve project:"); count != 1 {+ t.Fatalf("expected single 'resolve project:' prefix, got %d in %q", count, err.Error())+ }++ t.Setenv("MULTICA_WORKSPACE_ID", "")+ cmdMissingWS := newIssueSearchTestCmd()+ _ = cmdMissingWS.Flags().Set("project", "11111111")+ err = runIssueSearch(cmdMissingWS, []string{"deployment"})+ if err == nil {+ t.Fatal("expected error when workspace_id is missing for --project")+ }+ if !strings.Contains(err.Error(), "workspace_id is required") || strings.Contains(err.Error(), "resolve project:") {+ t.Fatalf("expected requireWorkspaceID error, got %q", err.Error())+ }+}++func TestIssueSearchCommandRegistration(t *testing.T) {+ for _, flagName := range []string{"limit", "include-closed", "project", "output"} {+ if issueSearchCmd.Flags().Lookup(flagName) == nil {+ t.Errorf("expected --%s flag on issue search command", flagName)+ }+ }+ if got := issueSearchCmd.Flags().Lookup("project").Usage; got != "Filter by project ID" {+ t.Errorf("project flag usage = %q, want %q", got, "Filter by project ID")+ }+}diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 50586c3c09..dbc88c92bd 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -800,7 +800,7 @@ type searchResult struct {// case-insensitive LIKE semantics as the legacy query. The pipeline deliberately// trades the title, description, and comment content GIN fast paths for one// predictable pass over each relation within the selected workspace.-func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string) (string, []any) {+func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool, terminalStatusKeys []string, projectID pgtype.UUID) (string, []any) {// Lowercase in Go so SQL only needs LOWER() on the column side.phrase = strings.ToLower(phrase)for i, term := range terms {@@ -838,6 +838,13 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,terminalStatusesParam = nextArg(terminalStatusKeys)}+ // Bound before limit/offset so the handler's args[len-2]/args[len-1] fill+ // keeps landing on the pagination placeholders.+ projectParam := ""+ if projectID.Valid {+ projectParam = nextArg(projectID)+ }+limitParam := nextArg(nil)offsetParam := nextArg(nil)@@ -880,6 +887,9 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,}issueWhere := "i.workspace_id = " + wsParam+ if projectParam != "" {+ issueWhere += " AND i.project_id = " + projectParam+ }if terminalStatusesParam != "" {issueWhere += fmt.Sprintf(" AND NOT (i.status = ANY(%s::text[]))", terminalStatusesParam)}@@ -951,10 +961,10 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,))commentWhere := "c.workspace_id = " + wsParam- if terminalStatusesParam != "" {- // Terminal issues cannot survive the issue_matches join in an open-only- // search; pruning them here skips LOWER(c.content) and BOOL_OR/ARRAY_AGG- // aggregation for closed issues' comments.+ if terminalStatusesParam != "" || projectParam != "" {+ // Prune comments for ineligible issues before LOWER(c.content) and+ // aggregation. Repeating the workspace predicate lets the planner drive+ // comment index lookups from eligible issues.commentWhere += fmt.Sprintf(" AND EXISTS (SELECT 1 FROM issue i WHERE i.id = c.issue_id AND %s)",issueWhere,@@ -1155,6 +1165,16 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {if !ok {return}++ // Malformed UUIDs return 400, matching ListIssues.+ var projectFilter pgtype.UUID+ if p := r.URL.Query().Get("project_id"); p != "" {+ id, ok := parseUUIDOrBadRequest(w, p, "project_id")+ if !ok {+ return+ }+ projectFilter = id+ }terms := splitSearchTerms(q)queryNum, hasNum := parseQueryNumber(q)var terminalStatusKeys []string@@ -1171,7 +1191,7 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {terminalStatusKeys = resolvedKeys}- sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, terminalStatusKeys)+ sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed, terminalStatusKeys, projectFilter)// Fill placeholder args: $4 = workspace_id, last two = limit, offsetargs[3] = wsUUIDargs[len(args)-2] = limitdiff --git a/server/internal/handler/search_candidate_parity_test.go b/server/internal/handler/search_candidate_parity_test.goindex bc62885e1d..01e484744d 100644--- a/server/internal/handler/search_candidate_parity_test.go+++ b/server/internal/handler/search_candidate_parity_test.go@@ -9,6 +9,7 @@ import ("time""github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/testutil")@@ -162,7 +163,7 @@ func TestBuildSearchQuery_CandidateFirstParity(t *testing.T) {legacyArgs[len(legacyArgs)-1] = tt.offsetcandidateQuery, candidateArgs := buildSearchQuery(- tt.phrase, append([]string(nil), terms...), tt.queryNum, tt.hasNum, tt.includeClosed, tt.terminalKeys,+ tt.phrase, append([]string(nil), terms...), tt.queryNum, tt.hasNum, tt.includeClosed, tt.terminalKeys, pgtype.UUID{},)candidateArgs[3] = testWorkspaceIDcandidateArgs[len(candidateArgs)-2] = tt.limit@@ -256,7 +257,7 @@ func runBuiltSearchForParity(t *testing.T, phrase string, includeClosed bool, tet.Helper()terms := splitSearchTerms(phrase)queryNum, hasNum := parseQueryNumber(phrase)- query, args := buildSearchQuery(phrase, terms, queryNum, hasNum, includeClosed, terminalKeys)+ query, args := buildSearchQuery(phrase, terms, queryNum, hasNum, includeClosed, terminalKeys, pgtype.UUID{})args[3] = testWorkspaceIDargs[len(args)-2] = limitargs[len(args)-1] = offsetdiff --git a/server/internal/handler/search_open_comments_test.go b/server/internal/handler/search_open_comments_test.goindex 97a7ae2223..55b71a02ec 100644--- a/server/internal/handler/search_open_comments_test.go+++ b/server/internal/handler/search_open_comments_test.go@@ -8,6 +8,7 @@ import ("testing""github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/testutil")@@ -37,6 +38,7 @@ func TestBuildSearchQuery_OpenCommentCandidates(t *testing.T) {false,includeClosed,[]string{"done", "cancelled", "verified"},+ pgtype.UUID{},)args[3], args[len(args)-2], args[len(args)-1] = parseUUID(testWorkspaceID), 20, 0// Inspect the candidate CTE directly: checking final search rows alonediff --git a/server/internal/handler/search_project_filter_test.go b/server/internal/handler/search_project_filter_test.gonew file mode 100644index 0000000000..5545804baf--- /dev/null+++ b/server/internal/handler/search_project_filter_test.go@@ -0,0 +1,81 @@+package handler++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestIssueSearch_ProjectFilter(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("requires DB")+ }++ token := fmt.Sprintf("mulprojsearch%d", time.Now().UnixNano())+ targetProjectID := dbfx.Project(t, "Target search project "+token)+ otherProjectID := dbfx.Project(t, "Other search project "+token)++ targetTitleIssueID := dbfx.Issue(t, token+" target title hit", testutil.Cols{+ "project_id": targetProjectID,+ })+ targetCommentIssueID := dbfx.Issue(t, "issue with comment hit in target project", testutil.Cols{+ "project_id": targetProjectID,+ })+ dbfx.Comment(t, targetCommentIssueID, token+" target comment hit")++ otherTitleIssueID := dbfx.Issue(t, token+" other project title hit", testutil.Cols{+ "project_id": otherProjectID,+ })+ otherCommentIssueID := dbfx.Issue(t, "issue with comment hit in other project", testutil.Cols{+ "project_id": otherProjectID,+ })+ dbfx.Comment(t, otherCommentIssueID, token+" other project comment hit")++ noProjectIssueID := dbfx.Issue(t, token+" unassigned project hit")++ params := url.Values{+ "q": {token},+ "project_id": {targetProjectID},+ }+ req := newRequest("GET", "/api/issues/search?"+params.Encode(), nil)+ w := testutil.Call(t, testHandler.SearchIssues, req).Want(http.StatusOK)++ var resp struct {+ Issues []SearchIssueResponse `json:"issues"`+ }+ w.JSON(&resp)++ gotIDs := make(map[string]bool, len(resp.Issues))+ for _, item := range resp.Issues {+ gotIDs[item.ID] = true+ }+ if !gotIDs[targetTitleIssueID] {+ t.Errorf("expected target project title-matched issue %s in results, got %+v", targetTitleIssueID, resp.Issues)+ }+ if !gotIDs[targetCommentIssueID] {+ t.Errorf("expected target project comment-matched issue %s in results, got %+v", targetCommentIssueID, resp.Issues)+ }+ if gotIDs[otherTitleIssueID] || gotIDs[otherCommentIssueID] || gotIDs[noProjectIssueID] {+ t.Errorf("expected non-target project issues to be excluded, got %+v", resp.Issues)+ }+}++func TestIssueSearch_ProjectFilterRejectsMalformedUUID(t *testing.T) {+ h := &Handler{}+ req := httptest.NewRequest("GET", "/api/issues/search?q=test&project_id=not-a-uuid", nil)+ req.Header.Set("X-User-ID", "00000000-0000-0000-0000-000000000002")+ req.Header.Set("X-Workspace-ID", "00000000-0000-0000-0000-000000000001")+ w := testutil.Call(t, h.SearchIssues, req).Want(http.StatusBadRequest)+ var resp struct {+ Error string `json:"error"`+ }+ w.JSON(&resp)+ if resp.Error != "invalid project_id" {+ t.Fatalf("error = %q, want %q", resp.Error, "invalid project_id")+ }+}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex 56a11d8565..133ebfd04a 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -1,12 +1,16 @@package handlerimport (+ "fmt""strings""testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype")func TestBuildSearchQuery_SingleTerm(t *testing.T) {- query, args := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, []string{"done", "cancelled"})+ query, args := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Pattern should be lowercased in Go.if args[0] != "hello" {@@ -48,7 +52,7 @@ func TestBuildSearchQuery_SingleTerm(t *testing.T) {}func TestBuildSearchQuery_OmitsUnusedExactTotal(t *testing.T) {- query, _ := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("Hello", []string{"Hello"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})if strings.Contains(query, "COUNT(*) OVER()") || strings.Contains(query, "total_count") {t.Fatalf("search query should not calculate an unused exact total:\n%s", query)@@ -72,6 +76,7 @@ func TestBuildSearchQuery_CustomTerminalStatuses(t *testing.T) {false,false,terminalStatusKeys,+ pgtype.UUID{},)if !strings.Contains(query, "NOT (i.status = ANY($5::text[]))") {@@ -89,7 +94,7 @@ func TestBuildSearchQuery_CustomTerminalStatuses(t *testing.T) {}func TestBuildSearchQuery_MultiTerm(t *testing.T) {- query, args := buildSearchQuery("Foo Bar", []string{"Foo", "Bar"}, 0, false, false, []string{"done", "cancelled"})+ query, args := buildSearchQuery("Foo Bar", []string{"Foo", "Bar"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Both phrase and terms should be lowercased.if args[0] != "foo bar" {@@ -110,7 +115,7 @@ func TestBuildSearchQuery_MultiTerm(t *testing.T) {}func TestBuildSearchQuery_LowersCommentContentOnce(t *testing.T) {- query, _ := buildSearchQuery("Foo Bar Baz", []string{"Foo", "Bar", "Baz"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("Foo Bar Baz", []string{"Foo", "Bar", "Baz"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})if count := strings.Count(query, "LOWER(c.content)"); count != 1 {t.Fatalf("query lowers comment content %d times, want exactly once:\n%s", count, query)@@ -133,7 +138,7 @@ func TestBuildSearchQuery_LowersCommentContentOnce(t *testing.T) {}func TestBuildSearchQuery_LowersIssueTextOnceAndSkipsDescriptionForTitleMatches(t *testing.T) {- query, _ := buildSearchQuery("Foo Bar Baz", []string{"Foo", "Bar", "Baz"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("Foo Bar Baz", []string{"Foo", "Bar", "Baz"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})normalizedQuery := strings.Join(strings.Fields(query), " ")if count := strings.Count(query, "LOWER(i.title)"); count != 1 {@@ -185,7 +190,7 @@ func assertSQLBefore(t *testing.T, query, earlier, later string) {}func TestBuildSearchQuery_WithNumber(t *testing.T) {- query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false, []string{"done", "cancelled"})+ query, args := buildSearchQuery("MUL-42", []string{"MUL-42"}, 42, true, false, []string{"done", "cancelled"}, pgtype.UUID{})_ = args// Number match should be in WHERE.@@ -199,7 +204,7 @@ func TestBuildSearchQuery_WithNumber(t *testing.T) {}func TestBuildSearchQuery_IncludeClosed(t *testing.T) {- query, _ := buildSearchQuery("test", []string{"test"}, 0, false, true, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("test", []string{"test"}, 0, false, true, []string{"done", "cancelled"}, pgtype.UUID{})if strings.Contains(query, "i.status = ANY(") {t.Error("query should not exclude done/cancelled when includeClosed=true")@@ -210,7 +215,7 @@ func TestBuildSearchQuery_IncludeClosed(t *testing.T) {}func TestBuildSearchQuery_SpecialChars(t *testing.T) {- query, args := buildSearchQuery("100%", []string{"100%"}, 0, false, false, []string{"done", "cancelled"})+ query, args := buildSearchQuery("100%", []string{"100%"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})_ = query// % should be escaped in the phrase arg.@@ -329,7 +334,7 @@ func TestExtractSnippet_CJKContent(t *testing.T) {// --- Ranking regression tests ---func TestBuildSearchQuery_CommentRankTiers(t *testing.T) {- query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Comment phrase match should be tier 7if !strings.Contains(query, "THEN 7") {@@ -346,7 +351,7 @@ func TestBuildSearchQuery_CommentRankTiers(t *testing.T) {}func TestBuildSearchQuery_DescriptionRankTiers(t *testing.T) {- query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Description phrase match should be tier 5if !strings.Contains(query, "THEN 5") {@@ -359,7 +364,7 @@ func TestBuildSearchQuery_DescriptionRankTiers(t *testing.T) {}func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {- query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Extract the rank CASE expression (ends with "ELSE 9 END") to avoid// false matches against statusRank which also contains THEN 4/6.@@ -390,7 +395,7 @@ func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {// $4 is buildSearchQuery's canonical workspace_id placeholder (the// caller writes wsUUID into args[3] before executing).func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {- singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, []string{"done", "cancelled"})+ singleQuery, _ := buildSearchQuery("html", []string{"html"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})// Candidate-first search aggregates comments in one workspace-first pass;// it must not grow a second scan for eligibility, ranking, or snippets.@@ -410,7 +415,7 @@ func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {}// Adding terms adds boolean aggregates, not extra comment relation scans.- multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"})+ multiQuery, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})fromCountMulti := strings.Count(multiQuery, "FROM comment c")if fromCountMulti != 1 {t.Errorf("multi-term query has %d comment scans, want exactly one:\n%s", fromCountMulti, multiQuery)@@ -424,7 +429,7 @@ func TestBuildSearchQuery_CommentSubqueryWorkspaceScope(t *testing.T) {}func TestBuildSearchQuery_HydratesOnlyTheSelectedPage(t *testing.T) {- query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"})+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})if strings.Contains(query, "issue_matches AS MATERIALIZED") {t.Fatalf("issue flag CTE must remain inlineable; forced materialization spills in production:\n%s", query)@@ -543,6 +548,98 @@ func TestBuildProjectSearchQuery_CancelledDemotedAheadOfRelevance(t *testing.T)// keeps each test's literals independent.func buildSearchQueryForTest(t *testing.T, phrase string, terms []string, num int, hasNum bool, includeClosed bool) string {t.Helper()- query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed, []string{"done", "cancelled"})+ query, _ := buildSearchQuery(phrase, append([]string(nil), terms...), num, hasNum, includeClosed, []string{"done", "cancelled"}, pgtype.UUID{})return query}++func TestBuildSearchQuery_ProjectFilter(t *testing.T) {+ unfilteredQuery, _ := buildSearchQuery("deploy", []string{"deploy"}, 0, false, false, []string{"done", "cancelled"}, pgtype.UUID{})+ if strings.Contains(unfilteredQuery, "i.project_id =") {+ t.Fatalf("unfiltered query should not contain project_id predicate:\n%s", unfilteredQuery)+ }+ if count := strings.Count(unfilteredQuery, "EXISTS (SELECT 1 FROM issue i"); count != 1 {+ t.Fatalf("unfiltered open-only query should retain one terminal-status comment EXISTS predicate, got %d:\n%s", count, unfilteredQuery)+ }++ rawProjectID := uuid.MustParse("11111111-2222-3333-4444-555555555555")+ projectFilter := pgtype.UUID{Bytes: rawProjectID, Valid: true}++ for _, tc := range []struct {+ name string+ phrase string+ terms []string+ queryNum int+ hasNum bool+ includeClosed bool+ terminalKeys []string+ wantProjectIdx int // 1-based SQL placeholder index for projectFilter+ wantArgCount int+ }{+ {+ name: "single term open only",+ phrase: "deploy",+ terms: []string{"deploy"},+ terminalKeys: []string{"done", "cancelled"},+ wantProjectIdx: 6,+ wantArgCount: 8,+ },+ {+ name: "multi term with number and closed included",+ phrase: "MUL-42 deploy",+ terms: []string{"MUL-42", "deploy"},+ queryNum: 42,+ hasNum: true,+ includeClosed: true,+ wantProjectIdx: 8,+ wantArgCount: 10,+ },+ } {+ t.Run(tc.name, func(t *testing.T) {+ filteredQuery, args := buildSearchQuery(+ tc.phrase,+ append([]string(nil), tc.terms...),+ tc.queryNum,+ tc.hasNum,+ tc.includeClosed,+ tc.terminalKeys,+ projectFilter,+ )+ if len(args) != tc.wantArgCount {+ t.Fatalf("len(args) = %d, want %d (%#v)", len(args), tc.wantArgCount, args)+ }+ if args[tc.wantProjectIdx-1] != projectFilter {+ t.Fatalf("args[%d] = %#v, want projectFilter %#v", tc.wantProjectIdx-1, args[tc.wantProjectIdx-1], projectFilter)+ }+ if args[len(args)-2] != nil || args[len(args)-1] != nil {+ t.Fatalf("trailing pagination placeholders must remain nil, got %#v", args[len(args)-2:])+ }++ commentCTEStart := strings.Index(filteredQuery, "comment_matches AS MATERIALIZED")+ if commentCTEStart == -1 {+ t.Fatalf("missing comment_matches CTE:\n%s", filteredQuery)+ }+ issueMatchesSection := filteredQuery[:commentCTEStart]+ wantIssueWhere := fmt.Sprintf("WHERE i.workspace_id = $4 AND i.project_id = $%d", tc.wantProjectIdx)+ if !strings.Contains(issueMatchesSection, wantIssueWhere) {+ t.Fatalf("issue_matches CTE missing %q:\n%s", wantIssueWhere, issueMatchesSection)+ }++ wantCommentWhere := fmt.Sprintf("i.workspace_id = $4 AND i.project_id = $%d", tc.wantProjectIdx)+ if !tc.includeClosed && len(tc.terminalKeys) > 0 {+ wantCommentWhere += fmt.Sprintf(" AND NOT (i.status = ANY($%d::text[]))", tc.wantProjectIdx-1)+ }+ wantCommentExists := "AND EXISTS (SELECT 1 FROM issue i WHERE i.id = c.issue_id AND " + wantCommentWhere + ")"+ if !strings.Contains(filteredQuery[commentCTEStart:], wantCommentExists) {+ t.Fatalf("comment_matches CTE missing %q:\n%s", wantCommentExists, filteredQuery[commentCTEStart:])+ }+ if count := strings.Count(filteredQuery, "EXISTS (SELECT 1 FROM issue i"); count != 1 {+ t.Fatalf("project and terminal-status filters should share one comment EXISTS predicate, got %d:\n%s", count, filteredQuery)+ }++ wantLimitOffset := fmt.Sprintf("LIMIT $%d OFFSET $%d", tc.wantProjectIdx+1, tc.wantProjectIdx+2)+ if !strings.Contains(filteredQuery, wantLimitOffset) {+ t.Fatalf("page_candidates CTE missing %q:\n%s", wantLimitOffset, filteredQuery)+ }+ })+ }+}