Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix: improve search ranking and snippet support (MUL-2329)
LinYushen66212312374a
diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 8576ef1047..698467defa 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -112,6 +112,8 @@ export interface ListIssuesCache {export interface SearchIssueResult extends Issue {match_source: "title" | "description" | "comment";matched_snippet?: string;+ matched_description_snippet?: string;+ matched_comment_snippet?: string;}export interface SearchIssuesResponse {diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 50a0f4d314..424034d36e 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -471,4 +471,64 @@ describe("SearchCommand", () => {expect(screen.getByText("Existing issue")).toBeInTheDocument();expect(screen.queryByText("deleted-issue")).not.toBeInTheDocument();});++ it("renders description and comment snippets regardless of match_source", async () => {+ const user = userEvent.setup();+ mockSearchIssues.mockResolvedValue({+ issues: [+ {+ id: "issue-snippet",+ workspace_id: "ws-test",+ number: 99,+ identifier: "MUL-99",+ title: "HTML rendering pipeline",+ description: null,+ status: "todo",+ priority: "none",+ assignee_type: null,+ assignee_id: null,+ creator_type: "member",+ creator_id: "user-1",+ parent_issue_id: null,+ project_id: null,+ position: 0,+ start_date: null,+ due_date: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ match_source: "title",+ matched_description_snippet: "...uses HTML templates for rendering...",+ matched_comment_snippet: "...we should migrate away from HTML...",+ },+ ],+ total: 1,+ });+ renderSearch();++ const input = screen.getByPlaceholderText("Type a command or search...");+ await user.type(input, "html");++ await waitFor(+ () => {+ expect(screen.getByText((_, el) => el?.textContent === "HTML rendering pipeline" && el?.tagName === "SPAN")).toBeInTheDocument();+ },+ { timeout: 2000 },+ );++ // Description snippet should render even though match_source is "title"+ expect(+ screen.getByText((_, el) =>+ (el?.textContent?.includes("uses HTML templates for rendering") ?? false) &&+ el?.tagName === "SPAN",+ ),+ ).toBeInTheDocument();++ // Comment snippet should render even though match_source is "title"+ expect(+ screen.getByText((_, el) =>+ (el?.textContent?.includes("we should migrate away from HTML") ?? false) &&+ el?.tagName === "SPAN",+ ),+ ).toBeInTheDocument();+ });});diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex 2f9b602fc9..88e285ff48 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -5,6 +5,7 @@ import {Check,Clock,Copy,+ FileText,Link2,Loader2,MessageSquare,@@ -64,8 +65,17 @@ import { useSearchStore } from "./search-store";function HighlightText({ text, query }: { text: string; query: string }) {const parts = useMemo(() => {if (!query.trim()) return [{ text, highlight: false }];- const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- const regex = new RegExp(`(${escaped})`, "gi");+ // Build regex that matches the full phrase OR individual terms+ const terms = query.trim().split(/\s+/).filter(Boolean);+ const escaped = query.trim().replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const patterns: string[] = [escaped];+ if (terms.length > 1) {+ for (const term of terms) {+ const e = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ if (e && !patterns.includes(e)) patterns.push(e);+ }+ }+ const regex = new RegExp(`(${patterns.join("|")})`, "gi");const result: { text: string; highlight: boolean }[] = [];let lastIndex = 0;let match: RegExpExecArray | null;@@ -661,18 +671,28 @@ export function SearchCommand() {{STATUS_CONFIG[issue.status].label}</span></div>- {issue.match_source === "comment" &&- issue.matched_snippet && (- <div className="flex items-start gap-2 pl-[26px]">- <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />- <span className="text-xs text-muted-foreground truncate">- <HighlightText- text={issue.matched_snippet}- query={query}- />- </span>- </div>- )}+ {issue.matched_description_snippet && (+ <div className="flex items-start gap-2 pl-[26px]">+ <FileText className="size-3 shrink-0 text-muted-foreground mt-0.5" />+ <span className="text-xs text-muted-foreground truncate">+ <HighlightText+ text={issue.matched_description_snippet}+ query={query}+ />+ </span>+ </div>+ )}+ {issue.matched_comment_snippet && (+ <div className="flex items-start gap-2 pl-[26px]">+ <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />+ <span className="text-xs text-muted-foreground truncate">+ <HighlightText+ text={issue.matched_comment_snippet}+ query={query}+ />+ </span>+ </div>+ )}</CommandPrimitive.Item>))}</CommandPrimitive.Group>diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex efd7995ea6..0dec18e5bc 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -191,31 +191,42 @@ func assigneeGroupID(assigneeType pgtype.Text, assigneeID pgtype.UUID) string {// SearchIssueResponse extends IssueResponse with search metadata.type SearchIssueResponse struct {IssueResponse- MatchSource string `json:"match_source"`- MatchedSnippet *string `json:"matched_snippet,omitempty"`+ MatchSource string `json:"match_source"`+ MatchedSnippet *string `json:"matched_snippet,omitempty"`+ MatchedDescriptionSnippet *string `json:"matched_description_snippet,omitempty"`+ MatchedCommentSnippet *string `json:"matched_comment_snippet,omitempty"`}// extractSnippet extracts a snippet of text around the first occurrence of query.// Returns up to ~120 runes centered on the match. Uses rune-based slicing to// avoid splitting multi-byte UTF-8 characters (important for CJK content).+// For multi-word queries, tries phrase match first; if not found, locates the+// earliest occurring individual term and centers the snippet around it.func extractSnippet(content, query string) string {runes := []rune(content)lowerRunes := []rune(strings.ToLower(content))queryRunes := []rune(strings.ToLower(query))- idx := -1- if len(queryRunes) > 0 && len(lowerRunes) >= len(queryRunes) {- for i := 0; i <= len(lowerRunes)-len(queryRunes); i++ {- match := true- for j := range queryRunes {- if lowerRunes[i+j] != queryRunes[j] {- match = false- break+ idx := findRuneSubstring(lowerRunes, queryRunes)++ // If phrase not found, try individual terms for multi-word queries.+ matchLen := len(queryRunes)+ if idx < 0 {+ terms := strings.Fields(strings.ToLower(query))+ if len(terms) > 1 {+ earliest := -1+ earliestLen := 0+ for _, term := range terms {+ termRunes := []rune(term)+ pos := findRuneSubstring(lowerRunes, termRunes)+ if pos >= 0 && (earliest < 0 || pos < earliest) {+ earliest = pos+ earliestLen = len(termRunes)}}- if match {- idx = i- break+ if earliest >= 0 {+ idx = earliest+ matchLen = earliestLen}}}@@ -230,7 +241,7 @@ func extractSnippet(content, query string) string {if start < 0 {start = 0}- end := idx + len(queryRunes) + 80+ end := idx + matchLen + 80if end > len(runes) {end = len(runes)}@@ -244,6 +255,46 @@ func extractSnippet(content, query string) string {return snippet}+// findRuneSubstring returns the index of needle in haystack, or -1 if not found.+func findRuneSubstring(haystack, needle []rune) int {+ if len(needle) == 0 || len(haystack) < len(needle) {+ return -1+ }+ for i := 0; i <= len(haystack)-len(needle); i++ {+ match := true+ for j := range needle {+ if haystack[i+j] != needle[j] {+ match = false+ break+ }+ }+ if match {+ return i+ }+ }+ return -1+}++// descriptionContains checks if the description text contains the search phrase or all terms.+func descriptionContains(desc pgtype.Text, phrase string, terms []string) bool {+ if !desc.Valid || desc.String == "" {+ return false+ }+ lower := strings.ToLower(desc.String)+ if strings.Contains(lower, strings.ToLower(phrase)) {+ return true+ }+ if len(terms) > 1 {+ for _, t := range terms {+ if !strings.Contains(lower, strings.ToLower(t)) {+ return false+ }+ }+ return true+ }+ return false+}+// escapeLike escapes LIKE special characters (%, _, \) in user input.func escapeLike(s string) string {s = strings.ReplaceAll(s, `\`, `\\`)@@ -297,6 +348,7 @@ type searchResult struct {// buildSearchQuery builds a dynamic SQL query for issue search.// It uses LOWER(column) LIKE for case-insensitive matching compatible with pg_bigm 1.2 GIN indexes.// Search patterns are lowercased in Go to avoid redundant LOWER() on the pattern side in SQL.+// LIKE patterns are pre-built in Go (e.g. "%html%") so pg_bigm can extract bigrams from a single parameter value.func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool, includeClosed bool) (string, []any) {// Lowercase in Go so SQL only needs LOWER() on the column side.phrase = strings.ToLower(phrase)@@ -315,19 +367,21 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,}escapedPhrase := escapeLike(phrase)- phraseParam := nextArg(escapedPhrase) // $1- phraseContains := "'%' || " + phraseParam + " || '%'"- phraseStartsWith := phraseParam + " || '%'"+ // $1: exact phrase (for exact title match)+ phraseParam := nextArg(escapedPhrase)+ // $2: "%phrase%" (contains pattern — pre-built for pg_bigm index usage)+ phraseContainsParam := nextArg("%" + escapedPhrase + "%")+ // $3: "phrase%" (starts-with pattern)+ phraseStartsWithParam := nextArg(escapedPhrase + "%")- wsParam := nextArg(nil) // $2 — workspace_id, will be filled by caller position+ wsParam := nextArg(nil) // $4 — workspace_id, will be filled by caller position// Build per-term LIKE conditions only for multi-word search.- // For single-word queries, the phrase parameter already covers the term.- var termParams []string+ var termContainsParams []stringif len(terms) > 1 {for _, t := range terms {et := escapeLike(t)- termParams = append(termParams, nextArg(et))+ termContainsParams = append(termContainsParams, nextArg("%"+et+"%"))}}@@ -337,18 +391,17 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,// Full phrase match: title, description, or commentphraseMatch := fmt.Sprintf("(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s))",- phraseContains, phraseContains, phraseContains,+ phraseContainsParam, phraseContainsParam, phraseContainsParam,)whereParts = append(whereParts, phraseMatch)// Multi-word AND match (each term must appear somewhere)- if len(termParams) > 1 {+ if len(termContainsParams) > 1 {var termConditions []string- for _, tp := range termParams {- tc := "'%' || " + tp + " || '%'"+ for _, tp := range termContainsParams {termConditions = append(termConditions, fmt.Sprintf("(LOWER(i.title) LIKE %s OR LOWER(COALESCE(i.description, '')) LIKE %s OR EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s))",- tc, tc, tc,+ tp, tp, tp,))}whereParts = append(whereParts, "("+strings.Join(termConditions, " AND ")+")")@@ -380,33 +433,45 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) = %s THEN 1", phraseParam))// Tier 2: Title starts with phrase- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 2", phraseStartsWith))+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 2", phraseStartsWithParam))// Tier 3: Title contains phrase- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 3", phraseContains))+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(i.title) LIKE %s THEN 3", phraseContainsParam))// Tier 4: Title matches all words (multi-word only)- if len(termParams) > 1 {+ if len(termContainsParams) > 1 {var titleTerms []string- for _, tp := range termParams {- titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE '%s' || %s || '%s'", "%", tp, "%"))+ for _, tp := range termContainsParams {+ titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))}rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 4", strings.Join(titleTerms, " AND ")))}// Tier 5: Description contains phrase- rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 5", phraseContains))+ rankCases = append(rankCases, fmt.Sprintf("WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 5", phraseContainsParam))// Tier 6: Description matches all words (multi-word only)- if len(termParams) > 1 {+ if len(termContainsParams) > 1 {var descTerms []string- for _, tp := range termParams {- descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE '%s' || %s || '%s'", "%", tp, "%"))+ for _, tp := range termContainsParams {+ descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))}rankCases = append(rankCases, fmt.Sprintf("WHEN (%s) THEN 6", strings.Join(descTerms, " AND ")))}- rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 7 END"+ // Tier 7: Comment contains phrase+ rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s) THEN 7", phraseContainsParam))++ // Tier 8: Comment matches all words (multi-word only)+ if len(termContainsParams) > 1 {+ var commentTerms []string+ for _, tp := range termContainsParams {+ commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))+ }+ rankCases = append(rankCases, fmt.Sprintf("WHEN EXISTS (SELECT 1 FROM comment c WHERE c.issue_id = i.id AND (%s)) THEN 8", strings.Join(commentTerms, " AND ")))+ }++ rankExpr := "CASE " + strings.Join(rankCases, " ") + " ELSE 9 END"// Status priority: active issues firststatusRank := `CASE i.status@@ -425,15 +490,15 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,WHEN LOWER(i.title) LIKE %s THEN 'title'WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN 'description'ELSE 'comment'- END`, phraseContains, phraseContains)+ END`, phraseContainsParam, phraseContainsParam)// For multi-word: also check if all terms match in title/description- if len(termParams) > 1 {+ if len(termContainsParams) > 1 {var titleTerms []stringvar descTerms []string- for _, tp := range termParams {- titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE '%s' || %s || '%s'", "%", tp, "%"))- descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE '%s' || %s || '%s'", "%", tp, "%"))+ for _, tp := range termContainsParams {+ titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE %s", tp))+ descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE %s", tp))}matchSourceExpr = fmt.Sprintf(`CASEWHEN LOWER(i.title) LIKE %s THEN 'title'@@ -442,50 +507,32 @@ func buildSearchQuery(phrase string, terms []string, queryNum int, hasNum bool,WHEN (%s) THEN 'description'ELSE 'comment'END`,- phraseContains, strings.Join(titleTerms, " AND "),- phraseContains, strings.Join(descTerms, " AND "),+ phraseContainsParam, strings.Join(titleTerms, " AND "),+ phraseContainsParam, strings.Join(descTerms, " AND "),)}// --- matched_comment_content subquery ---- // Find the most recent matching comment for comment-source matches.- commentSubquery := fmt.Sprintf(`CASE- WHEN LOWER(i.title) LIKE %s THEN ''- WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN ''- ELSE COALESCE(+ // Always return matching comment content regardless of match_source,+ // so frontend can display comment snippet alongside title/description matches.+ commentSubquery := fmt.Sprintf(`COALESCE(+ (SELECT c.content FROM comment c+ WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s+ ORDER BY c.created_at DESC LIMIT 1),+ ''+ )`, phraseContainsParam)++ if len(termContainsParams) > 1 {+ var commentTerms []string+ for _, tp := range termContainsParams {+ commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE %s", tp))+ }+ commentSubquery = fmt.Sprintf(`COALESCE((SELECT c.content FROM comment c- WHERE c.issue_id = i.id AND LOWER(c.content) LIKE %s+ WHERE c.issue_id = i.id AND (LOWER(c.content) LIKE %s OR (%s))ORDER BY c.created_at DESC LIMIT 1),''- )- END`, phraseContains, phraseContains, phraseContains)-- // For multi-word, also find comment matching individual terms- if len(termParams) > 1 {- var titleTerms []string- var descTerms []string- var commentTerms []string- for _, tp := range termParams {- titleTerms = append(titleTerms, fmt.Sprintf("LOWER(i.title) LIKE '%s' || %s || '%s'", "%", tp, "%"))- descTerms = append(descTerms, fmt.Sprintf("LOWER(COALESCE(i.description, '')) LIKE '%s' || %s || '%s'", "%", tp, "%"))- commentTerms = append(commentTerms, fmt.Sprintf("LOWER(c.content) LIKE '%s' || %s || '%s'", "%", tp, "%"))- }- commentSubquery = fmt.Sprintf(`CASE- WHEN LOWER(i.title) LIKE %s THEN ''- WHEN (%s) THEN ''- WHEN LOWER(COALESCE(i.description, '')) LIKE %s THEN ''- WHEN (%s) THEN ''- ELSE COALESCE(- (SELECT c.content FROM comment c- WHERE c.issue_id = i.id AND (LOWER(c.content) LIKE %s OR (%s))- ORDER BY c.created_at DESC LIMIT 1),- ''- )- END`,- phraseContains, strings.Join(titleTerms, " AND "),- phraseContains, strings.Join(descTerms, " AND "),- phraseContains, strings.Join(commentTerms, " AND "),- )+ )`, phraseContainsParam, strings.Join(commentTerms, " AND "))}limitParam := nextArg(nil) // placeholder@@ -551,8 +598,8 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {queryNum, hasNum := parseQueryNumber(q)sqlQuery, args := buildSearchQuery(q, terms, queryNum, hasNum, includeClosed)- // Fill placeholder args: $2 = workspace_id, last two = limit, offset- args[1] = wsUUID+ // Fill placeholder args: $4 = workspace_id, last two = limit, offset+ args[3] = wsUUIDargs[len(args)-2] = limitargs[len(args)-1] = offset@@ -616,9 +663,21 @@ func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {IssueResponse: issueToResponse(sr.issue, prefix),MatchSource: sr.matchSource,}- if sr.matchSource == "comment" && sr.matchedCommentContent != "" {+ // Always populate comment snippet when a matching comment exists+ if sr.matchedCommentContent != "" {snippet := extractSnippet(sr.matchedCommentContent, q)- sir.MatchedSnippet = &snippet+ sir.MatchedCommentSnippet = &snippet+ // Keep backward compat: also set MatchedSnippet for comment-source matches+ if sr.matchSource == "comment" {+ sir.MatchedSnippet = &snippet+ }+ }+ // Populate description snippet when description matches+ if sr.matchSource == "description" || descriptionContains(sr.issue.Description, q, terms) {+ if sr.issue.Description.Valid && sr.issue.Description.String != "" {+ snippet := extractSnippet(sr.issue.Description.String, q)+ sir.MatchedDescriptionSnippet = &snippet+ }}resp[i] = sir}diff --git a/server/internal/handler/search_test.go b/server/internal/handler/search_test.goindex 5f35fbd896..e27af9abdc 100644--- a/server/internal/handler/search_test.go+++ b/server/internal/handler/search_test.go@@ -48,12 +48,12 @@ func TestBuildSearchQuery_MultiTerm(t *testing.T) {if args[0] != "foo bar" {t.Errorf("expected phrase arg lowercased, got %q", args[0])}- // args[1] is workspace_id placeholder; term args start at args[2].- if args[2] != "foo" {- t.Errorf("expected first term arg lowercased, got %q", args[2])+ // args[0]=exact, args[1]=%phrase%, args[2]=phrase%, args[3]=workspace_id placeholder; term args start at args[4].+ if args[4] != "%foo%" {+ t.Errorf("expected first term arg as contains pattern, got %q", args[4])}- if args[3] != "bar" {- t.Errorf("expected second term arg lowercased, got %q", args[3])+ if args[5] != "%bar%" {+ t.Errorf("expected second term arg as contains pattern, got %q", args[5])}// Multi-word query should have AND conditions.@@ -144,3 +144,114 @@ func TestBuildProjectSearchQuery_IncludeClosed(t *testing.T) {t.Error("query should not exclude completed/cancelled when includeClosed=true")}}++// --- extractSnippet regression tests ---++func TestExtractSnippet_PhraseMatch(t *testing.T) {+ content := "The quick brown fox jumps over the lazy dog near the river bank"+ snippet := extractSnippet(content, "brown fox")+ if !strings.Contains(snippet, "brown fox") {+ t.Errorf("snippet should contain the phrase 'brown fox', got %q", snippet)+ }+}++func TestExtractSnippet_MultiWordNonContiguous(t *testing.T) {+ // "deploy" and "kubernetes" both appear but not as a contiguous phrase.+ content := "We need to deploy the new service. The kubernetes cluster is ready for production workloads."+ snippet := extractSnippet(content, "deploy kubernetes")+ // Should NOT fall back to first 120 chars blindly — should center on earliest term.+ if !strings.Contains(strings.ToLower(snippet), "deploy") && !strings.Contains(strings.ToLower(snippet), "kubernetes") {+ t.Errorf("snippet should contain at least one search term, got %q", snippet)+ }+ // Specifically, "deploy" appears first so snippet should be centered around it.+ if !strings.Contains(strings.ToLower(snippet), "deploy") {+ t.Errorf("snippet should center on earliest term 'deploy', got %q", snippet)+ }+}++func TestExtractSnippet_FallbackWhenNoMatch(t *testing.T) {+ content := strings.Repeat("a", 200)+ snippet := extractSnippet(content, "zzz")+ if len([]rune(snippet)) > 124 { // 120 + "..."+ t.Errorf("snippet should be truncated to ~120 runes when no match, got len=%d", len([]rune(snippet)))+ }+}++func TestExtractSnippet_ShortContent(t *testing.T) {+ content := "short text"+ snippet := extractSnippet(content, "missing")+ if snippet != content {+ t.Errorf("short content with no match should return as-is, got %q", snippet)+ }+}++func TestExtractSnippet_CaseInsensitive(t *testing.T) {+ content := "Error in HTML rendering pipeline"+ snippet := extractSnippet(content, "html")+ if !strings.Contains(snippet, "HTML") {+ t.Errorf("snippet should find case-insensitive match, got %q", snippet)+ }+}++func TestExtractSnippet_CJKContent(t *testing.T) {+ content := "这是一段很长的中文内容,包含了搜索关键词测试用例,用来验证多字节字符不会被截断的情况"+ snippet := extractSnippet(content, "搜索关键词")+ if !strings.Contains(snippet, "搜索关键词") {+ t.Errorf("snippet should contain CJK phrase, got %q", snippet)+ }+}++// --- Ranking regression tests ---++func TestBuildSearchQuery_CommentRankTiers(t *testing.T) {+ query, _ := buildSearchQuery("test phrase", []string{"test", "phrase"}, 0, false, false)++ // Comment phrase match should be tier 7+ if !strings.Contains(query, "THEN 7") {+ t.Error("query should contain tier 7 for comment phrase match")+ }+ // Comment all-term match should be tier 8+ if !strings.Contains(query, "THEN 8") {+ t.Error("query should contain tier 8 for comment all-term match")+ }+ // Fallback should be 9, not 7+ if !strings.Contains(query, "ELSE 9") {+ t.Error("query fallback should be ELSE 9")+ }+}++func TestBuildSearchQuery_DescriptionRankTiers(t *testing.T) {+ query, _ := buildSearchQuery("foo bar", []string{"foo", "bar"}, 0, false, false)++ // Description phrase match should be tier 5+ if !strings.Contains(query, "THEN 5") {+ t.Error("query should contain tier 5 for description phrase match")+ }+ // Description all-term match should be tier 6+ if !strings.Contains(query, "THEN 6") {+ t.Error("query should contain tier 6 for description all-term match")+ }+}++func TestBuildSearchQuery_SingleTermNoAllTermTiers(t *testing.T) {+ query, _ := buildSearchQuery("html", []string{"html"}, 0, false, false)++ // Extract the rank CASE expression (ends with "ELSE 9 END") to avoid+ // false matches against statusRank which also contains THEN 4/6.+ rankEnd := strings.Index(query, "ELSE 9 END")+ if rankEnd == -1 {+ t.Fatal("query should contain rank expression with ELSE 9 END")+ }+ rankExpr := query[:rankEnd]++ // Single-term queries should NOT have tier 4 (title all-terms), 6 (desc all-terms), or 8 (comment all-terms)+ if strings.Contains(rankExpr, "THEN 4") {+ t.Error("single-term query should not have tier 4 (title all-terms)")+ }+ if strings.Contains(rankExpr, "THEN 6") {+ t.Error("single-term query should not have tier 6 (description all-terms)")+ }+ if strings.Contains(rankExpr, "THEN 8") {+ t.Error("single-term query should not have tier 8 (comment all-terms)")+ }+}