Skip to content

LLM Wiki is a cross-platform desktop application that turns your documents into an organized, interlinked knowledge base — automatically. Instead of traditional RAG (retrieve-and-answer from scratch every time), the LLM incrementally builds and maintains a persistent wiki from your sources。

TypeScript

fix: ground research queries in project context

nash_sua799001df0a4
diff --git a/src/components/graph/graph-view.tsx b/src/components/graph/graph-view.tsx
index 2f4d03f1..a5796885 100644
--- a/src/components/graph/graph-view.tsx
+++ b/src/components/graph/graph-view.tsx
@@ -14,9 +14,10 @@ import { readFile, writeFile } from "@/commands/fs"
import { WikiEditor } from "@/components/editor/wiki-editor"
import { FilePreview } from "@/components/editor/file-preview"
import { buildWikiGraph, type GraphNode, type GraphEdge, type CommunityInfo } from "@/lib/wiki-graph"
-import { findSurprisingConnections, detectKnowledgeGaps, type SurprisingConnection, type KnowledgeGap } from "@/lib/graph-insights"
+import { findSurprisingConnections, detectKnowledgeGaps, researchSeedForKnowledgeGap, type SurprisingConnection, type KnowledgeGap } from "@/lib/graph-insights"
import { queueResearch } from "@/lib/deep-research"
import { optimizeResearchTopic } from "@/lib/optimize-research-topic"
+import { groundedFallbackResearchQuery } from "@/lib/research-query-grounding"
import { getFileName, normalizePath } from "@/lib/path-utils"
import { getFileCategory } from "@/lib/file-types"
import { applyGraphFilters, hasActiveGraphFilters, type GraphFilterState } from "@/lib/graph-filters"
@@ -811,12 +812,13 @@ export function GraphView() {
}
}, [highlightedNodes])
- const handleResearchClick = useCallback(async (gapTitle: string, gapDescription: string, gapType: string, dismissKey?: string) => {
+ const handleResearchClick = useCallback(async (gap: KnowledgeGap, dismissKey?: string) => {
const store = useWikiStore.getState()
if (!store.project) return
const pp = normalizePath(store.project.path)
const token = researchDialogTokenRef.current + 1
researchDialogTokenRef.current = token
+ const { term: gapTerm, context: gapContext } = researchSeedForKnowledgeGap(gap, nodes)
// Show loading state
setResearchDialog({ loading: true, topic: "", queries: [], dismissKey })
@@ -830,9 +832,9 @@ export function GraphView() {
const result = await optimizeResearchTopic(
store.llmConfig,
- gapTitle,
- gapDescription,
- gapType,
+ gapTerm,
+ gapContext,
+ gap.type,
overview,
purpose,
)
@@ -840,10 +842,14 @@ export function GraphView() {
setResearchDialog({ loading: false, topic: result.topic, queries: result.searchQueries, dismissKey })
} catch {
if (researchDialogTokenRef.current !== token) return
- // Fallback: use raw title
- setResearchDialog({ loading: false, topic: gapTitle, queries: [gapTitle], dismissKey })
+ setResearchDialog({
+ loading: false,
+ topic: gapTerm,
+ queries: [groundedFallbackResearchQuery(gapTerm, gapContext)],
+ dismissKey,
+ })
}
- }, [])
+ }, [nodes])
const handleResearchConfirm = useCallback(() => {
if (!researchDialog) return
@@ -1594,7 +1600,7 @@ export function GraphView() {
className="h-7 text-xs gap-1"
onClick={(e) => {
e.stopPropagation()
- handleResearchClick(gap.title, gap.description, gap.type, gapKey)
+ handleResearchClick(gap, gapKey)
}}
>
<Search className="h-3.5 w-3.5" />
diff --git a/src/components/review/review-view.tsx b/src/components/review/review-view.tsx
index 306acc6a..3fd17f19 100644
--- a/src/components/review/review-view.tsx
+++ b/src/components/review/review-view.tsx
@@ -25,7 +25,7 @@ import { cleanAssistantContentForWikiSave, titleFromCleanAssistantContent } from
import { useTranslation } from "react-i18next"
import { useAppDialog } from "@/stores/app-dialog-store"
import { useResearchStore } from "@/stores/research-store"
-import { reviewResearchTopic, selectedResearchReviews } from "@/lib/review-batch-research"
+import { reviewResearchQueries, reviewResearchTopic, selectedResearchReviews } from "@/lib/review-batch-research"
const typeConfig: Record<ReviewItem["type"], { icon: typeof AlertTriangle; color: string }> = {
contradiction: { icon: AlertTriangle, color: "text-amber-500" },
@@ -101,7 +101,14 @@ export function ReviewView() {
const llmConfig = useWikiStore.getState().llmConfig
// Use pre-generated search queries if available, otherwise fall back to title
const topic = item.title.replace(/^(Save to Wiki|Create|Research)[:\s]*/i, "").trim() || item.description.split("\n")[0]
- queueResearch(pp, topic, llmConfig, searchConfig, item.searchQueries, id)
+ queueResearch(
+ pp,
+ topic,
+ llmConfig,
+ searchConfig,
+ reviewResearchQueries(item, topic),
+ id,
+ )
} else {
resolveItem(id, action)
}
@@ -210,7 +217,14 @@ export function ReviewView() {
if (item) {
const llmConfig = useWikiStore.getState().llmConfig
const topic = action.replace(/^research\s*/i, "").trim() || item.description.split("\n")[0]
- queueResearch(pp, topic, llmConfig, searchConfig, undefined, id)
+ queueResearch(
+ pp,
+ topic,
+ llmConfig,
+ searchConfig,
+ reviewResearchQueries({ ...item, searchQueries: undefined }, topic),
+ id,
+ )
} else {
resolveItem(id, action)
}
@@ -366,7 +380,7 @@ export function ReviewView() {
normalizePath(project.path),
eligibleItems.map((item) => ({
topic: reviewResearchTopic(item),
- searchQueries: item.searchQueries,
+ searchQueries: reviewResearchQueries(item),
sourceReviewId: item.id,
})),
state.llmConfig,
diff --git a/src/lib/graph-insights.test.ts b/src/lib/graph-insights.test.ts
index ef1e56dd..59ce7ca9 100644
--- a/src/lib/graph-insights.test.ts
+++ b/src/lib/graph-insights.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest"
-import { detectKnowledgeGaps } from "./graph-insights"
+import { detectKnowledgeGaps, researchSeedForKnowledgeGap } from "./graph-insights"
import type { CommunityInfo, GraphNode } from "./wiki-graph"
function nodes(count: number): GraphNode[] {
@@ -39,3 +39,35 @@ describe("detectKnowledgeGaps sparse communities", () => {
.toContain("1.4 internal links per page")
})
})
+
+describe("researchSeedForKnowledgeGap", () => {
+ it("uses one actual page label for an isolated-page group", () => {
+ const graphNodes = nodes(3)
+ const seed = researchSeedForKnowledgeGap({
+ type: "isolated-node",
+ title: "3 isolated pages",
+ description: "Node 0, Node 1, Node 2",
+ nodeIds: graphNodes.map((node) => node.id),
+ suggestion: "Research them",
+ }, graphNodes)
+ expect(seed).toEqual({ term: "Node 0", context: "" })
+ })
+
+ it("prioritizes the most connected sparse-cluster node without UI metadata", () => {
+ const graphNodes = nodes(3).map((node, index) => ({
+ ...node,
+ linkCount: [1, 8, 4][index],
+ }))
+ const seed = researchSeedForKnowledgeGap({
+ type: "sparse-community",
+ title: "Sparse cluster: generated label",
+ description: "3 pages average 1.0 internal links per page.",
+ nodeIds: graphNodes.map((node) => node.id),
+ suggestion: "Research it",
+ }, graphNodes)
+ expect(seed.term).toBe("Node 1")
+ expect(seed.context).toBe("Node 2 Node 0")
+ expect(`${seed.term} ${seed.context}`).not.toContain("Sparse cluster")
+ expect(`${seed.term} ${seed.context}`).not.toContain("internal links")
+ })
+})
diff --git a/src/lib/graph-insights.ts b/src/lib/graph-insights.ts
index 87108999..7135f206 100644
--- a/src/lib/graph-insights.ts
+++ b/src/lib/graph-insights.ts
@@ -20,6 +20,27 @@ export interface KnowledgeGap {
suggestion: string
}
+export function researchSeedForKnowledgeGap(
+ gap: KnowledgeGap,
+ nodes: readonly GraphNode[],
+): { term: string; context: string } {
+ const candidates = gap.nodeIds
+ .map((id) => nodes.find((node) => node.id === id))
+ .filter((node): node is GraphNode => Boolean(node))
+
+ if (gap.type === "isolated-node") {
+ return { term: candidates[0]?.label || gap.title, context: "" }
+ }
+
+ candidates.sort((a, b) => b.linkCount - a.linkCount)
+ const representative = candidates[0]?.label || gap.title
+ const related = candidates.slice(1, 3).map((node) => node.label)
+ return {
+ term: representative,
+ context: related.length > 0 ? related.join(" ") : "",
+ }
+}
+
// ---------------------------------------------------------------------------
// Surprising Connections
// ---------------------------------------------------------------------------
diff --git a/src/lib/ingest.prompt.test.ts b/src/lib/ingest.prompt.test.ts
index 57e77ac6..7be7f884 100644
--- a/src/lib/ingest.prompt.test.ts
+++ b/src/lib/ingest.prompt.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, beforeEach } from "vitest"
import {
+ buildReviewSuggestionPrompt,
buildAnalysisPrompt,
buildGenerationPrompt,
buildPageMergeSystemPrompt,
@@ -202,6 +203,40 @@ describe("page merge prompt", () => {
})
})
+describe("review research query prompt", () => {
+ it("grounds ambiguous internal terms before generating web queries", () => {
+ const prompt = buildReviewSuggestionPrompt(
+ "A private cognitive-analysis project",
+ "- [[attention-filter]]",
+ "internal-notes.md",
+ "AF is the project's attention-filter signal.",
+ "The pipeline dispatches AF events between internal modules.",
+ "---FILE: wiki/concepts/attention-filter.md---",
+ 128_000,
+ )
+
+ expect(prompt).toContain("project-local vocabulary")
+ expect(prompt).toContain("Never emit a bare ambiguous term as a web query")
+ expect(prompt).toContain("Do not substitute a popular public meaning")
+ expect(prompt).toContain("underlying real-world concepts or comparisons")
+ expect(prompt).toContain("AF is the project's attention-filter signal")
+ })
+
+ it("applies the same grounding rules to the main generation path", () => {
+ const prompt = buildGenerationPrompt(
+ "A private cognitive-analysis project",
+ "- [[attention-filter]]",
+ "Project overview",
+ "internal-notes.md",
+ "AF is the project's attention-filter signal.",
+ )
+
+ expect(prompt).toContain("project-local vocabulary")
+ expect(prompt).toContain("Never emit a bare ambiguous term as a web query")
+ expect(prompt).toContain("Do not substitute a popular public meaning")
+ })
+})
+
describe("long-source ingest planning", () => {
it("scales generation output tokens with the configured context window", () => {
expect(computeIngestGenerationMaxTokens(64_000)).toBe(8_192)
diff --git a/src/lib/ingest.ts b/src/lib/ingest.ts
index 2b12ddd5..ddd8f3f7 100644
--- a/src/lib/ingest.ts
+++ b/src/lib/ingest.ts
@@ -47,6 +47,7 @@ import { GENERATION_WIKI_TYPES } from "@/lib/wiki-page-types"
import { computeContextBudget } from "@/lib/context-budget"
import { refreshProjectFileTree } from "@/lib/project-file-tree-refresh"
import { persistParsedMarkdown } from "@/lib/parsed-source-output"
+import { PROJECT_LOCAL_TERM_QUERY_RULES } from "@/lib/research-query-grounding"
const LONG_SOURCE_MIN_BUDGET = 8_000
const LONG_SOURCE_MAX_SINGLE_PASS_BUDGET = 300_000
@@ -2393,7 +2394,9 @@ export function buildGenerationPrompt(
"Do NOT invent custom option labels. Only use 'Create Page' and 'Skip'.",
"",
"For suggestion and missing-page reviews, the SEARCH field must contain 2-3 web search queries",
- "(keyword-rich, specific, suitable for a search engine — NOT titles or sentences). Example:",
+ "(concise, context-grounded, suitable for a search engine — NOT titles or sentences).",
+ ...PROJECT_LOCAL_TERM_QUERY_RULES,
+ "Example:",
" SEARCH: automated technical debt detection AI generated code | software quality metrics LLM code generation | static analysis tools agentic software development",
"",
purpose ? `## Wiki Purpose\n${purpose}` : "",
@@ -2443,7 +2446,7 @@ export function buildGenerationPrompt(
].filter(Boolean).join("\n")
}
-function buildReviewSuggestionPrompt(
+export function buildReviewSuggestionPrompt(
purpose: string,
index: string,
sourceIdentity: string,
@@ -2471,7 +2474,8 @@ function buildReviewSuggestionPrompt(
"- duplicate: likely duplicate pages/names that need user review",
"",
"Prefer 1-5 high-signal reviews. If there is nothing worth reviewing, output nothing.",
- "For suggestion and missing-page reviews, include a SEARCH line with 2-3 keyword-rich web search queries separated by ` | `.",
+ "For suggestion and missing-page reviews, include a SEARCH line with 2-3 context-grounded web search queries separated by ` | `.",
+ ...PROJECT_LOCAL_TERM_QUERY_RULES,
"Use only these options: OPTIONS: Create Page | Skip",
"",
"REVIEW block template:",
diff --git a/src/lib/optimize-research-topic.test.ts b/src/lib/optimize-research-topic.test.ts
index 2fbf194d..1e8ee905 100644
--- a/src/lib/optimize-research-topic.test.ts
+++ b/src/lib/optimize-research-topic.test.ts
@@ -121,3 +121,41 @@ describe("optimizeResearchTopic — response parsing", () => {
expect(result.searchQueries).toHaveLength(3)
})
})
+
+describe("optimizeResearchTopic — project-local vocabulary", () => {
+ it("requires ambiguous internal terms to remain grounded in wiki context", async () => {
+ await optimizeResearchTopic(
+ fakeLlmConfig(),
+ "AF",
+ "An attention-filter signal used by the project pipeline",
+ "missing-page",
+ "The wiki documents a private cognitive-analysis system.",
+ "Explain the project's signal-processing architecture.",
+ )
+
+ const prompt = mockStreamChat.mock.calls[0][1][0].content
+ expect(prompt).toContain("project-local vocabulary")
+ expect(prompt).toContain("Never emit a bare ambiguous term as a web query")
+ expect(prompt).toContain("Do not substitute a popular public meaning")
+ expect(prompt).toContain("no likely public documentation")
+ expect(prompt).toContain("An attention-filter signal used by the project pipeline")
+ })
+
+ it("expands a bare model query with local context", async () => {
+ mockStreamChatReturns("TOPIC: AF\nQUERY: AF")
+
+ const result = await optimizeResearchTopic(
+ fakeLlmConfig(),
+ "AF",
+ "attention filter signal in a cognitive-analysis pipeline",
+ "missing-page",
+ "",
+ "",
+ )
+
+ expect(result.searchQueries).toHaveLength(1)
+ expect(result.searchQueries[0]).toContain("AF")
+ expect(result.searchQueries[0]).toContain("attention filter signal")
+ expect(result.searchQueries[0]).not.toBe("AF")
+ })
+})
diff --git a/src/lib/optimize-research-topic.ts b/src/lib/optimize-research-topic.ts
index 09feb437..dacb44d8 100644
--- a/src/lib/optimize-research-topic.ts
+++ b/src/lib/optimize-research-topic.ts
@@ -1,6 +1,11 @@
import { streamChat } from "./llm-client"
import type { LlmConfig } from "@/stores/wiki-store"
import { buildLanguageDirective } from "./output-language"
+import {
+ groundBareResearchQueries,
+ groundedFallbackResearchQuery,
+ PROJECT_LOCAL_TERM_QUERY_RULES,
+} from "./research-query-grounding"
export interface OptimizedTopic {
topic: string
@@ -35,8 +40,10 @@ export async function optimizeResearchTopic(
"",
"## Task",
"Generate a research topic and search queries that are specific to this wiki's domain and purpose.",
+ ...PROJECT_LOCAL_TERM_QUERY_RULES,
+ "Use the local description as the authoritative meaning of the term.",
"The topic should precisely describe what information would fill this knowledge gap.",
- "The search queries should be optimized for web search engines — keyword-rich, specific, not generic.",
+ "The search queries should be concise and specific while retaining the exact original-language project term.",
"",
"## Output Format (STRICT — follow exactly, no other text)",
"Respond with EXACTLY 4 lines, no more:",
@@ -62,14 +69,26 @@ export async function optimizeResearchTopic(
const topicMatch = result.match(/^TOPIC:\s*(.+)$/m)
const queryMatches = [...result.matchAll(/^QUERY:\s*(.+)$/gm)]
- const topic = topicMatch?.[1]?.trim() ?? gapTitle
- const searchQueries = queryMatches
+ const topic = topicMatch?.[1]?.trim() || gapTitle
+ // Deterministic fallbacks go directly to a third-party search provider.
+ // Keep them to the explicit gap description; purpose/overview remain prompt
+ // context for the configured LLM but are not copied verbatim into web queries.
+ const queryContext = gapDescription
+ const parsedQueries = queryMatches
.slice(0, 3)
.map((m) => m[1].trim())
.filter((q) => q.length > 0)
+ const searchQueries = groundBareResearchQueries(
+ parsedQueries.length > 0 ? parsedQueries : [topic],
+ gapTitle,
+ queryContext,
+ [topic],
+ )
return {
topic,
- searchQueries: searchQueries.length > 0 ? searchQueries : [topic],
+ searchQueries: searchQueries.length > 0
+ ? searchQueries
+ : [groundedFallbackResearchQuery(gapTitle, queryContext)],
}
}
diff --git a/src/lib/research-query-grounding.test.ts b/src/lib/research-query-grounding.test.ts
new file mode 100644
index 00000000..f4752434
--- /dev/null
+++ b/src/lib/research-query-grounding.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from "vitest"
+import {
+ groundBareResearchQueries,
+ groundedFallbackResearchQuery,
+} from "./research-query-grounding"
+
+describe("research query grounding", () => {
+ it("keeps the exact local term while adding context", () => {
+ expect(groundedFallbackResearchQuery(
+ "AF",
+ "An attention-filter signal in the project pipeline.",
+ )).toBe("AF An attention-filter signal in the project pipeline.")
+ })
+
+ it("replaces only bare topic queries", () => {
+ expect(groundBareResearchQueries(
+ ["AF", "AF attention filter cognitive signal"],
+ "AF",
+ "attention-filter signal",
+ )).toEqual([
+ "AF attention-filter signal",
+ "AF attention filter cognitive signal",
+ ])
+ })
+
+ it("preserves special characters in non-bare model queries", () => {
+ expect(groundBareResearchQueries(
+ ["C# async await", "snake_case naming", "F# pattern matching", "site:https://example.com AF"],
+ "AF",
+ "attention filter",
+ )).toEqual([
+ "C# async await",
+ "snake_case naming",
+ "F# pattern matching",
+ "site:https://example.com AF",
+ ])
+ })
+
+ it("normalizes wrapped bare terms and removes duplicate searches", () => {
+ expect(groundBareResearchQueries(
+ ["AF", "af", "[[AF]]", "\"AF\""],
+ "AF",
+ "attention filter",
+ )).toEqual(["AF attention filter"])
+ })
+
+ it("removes prompt-shaping Markdown and URLs from fallback context", () => {
+ const query = groundedFallbackResearchQuery(
+ "[[Hana]]",
+ "# Module `Hana` details https://example.test/private",
+ )
+ expect(query).toBe("Hana Module Hana details")
+ })
+
+ it("keeps CJK terms and caps long fallback context at a word boundary", () => {
+ const query = groundedFallbackResearchQuery("灵犀", "context ".repeat(100))
+ expect(query.startsWith("灵犀 ")).toBe(true)
+ expect(Array.from(query).length).toBeLessThanOrEqual(280)
+ expect(query.endsWith(" ")).toBe(false)
+ })
+
+ it("does not discard long CJK context without spaces", () => {
+ const query = groundedFallbackResearchQuery("灵犀", `AI ${"中".repeat(300)}`)
+ expect(Array.from(query).filter((character) => character === "中").length)
+ .toBeGreaterThanOrEqual(150)
+ })
+})
diff --git a/src/lib/research-query-grounding.ts b/src/lib/research-query-grounding.ts
new file mode 100644
index 00000000..7dc5c228
--- /dev/null
+++ b/src/lib/research-query-grounding.ts
@@ -0,0 +1,73 @@
+export const PROJECT_LOCAL_TERM_QUERY_RULES = [
+ "Treat ambiguous names, acronyms, character names, module names, and ordinary-looking labels as project-local vocabulary unless the supplied context clearly identifies a public meaning.",
+ "Never emit a bare ambiguous term as a web query. Preserve its exact spelling and add domain, project, entity, or mechanism keywords supported by the supplied context.",
+ "Do not substitute a popular public meaning for a project-local meaning.",
+ "If an internal term has no likely public documentation, search for the underlying real-world concepts or comparisons needed to fill the gap.",
+] as const
+
+const TERM_MAX_LENGTH = 120
+const CONTEXT_MAX_LENGTH = 180
+const QUERY_MAX_LENGTH = 280
+
+function truncateAtWord(value: string, maxLength: number): string {
+ const characters = Array.from(value)
+ if (characters.length <= maxLength) return value
+ const truncated = characters.slice(0, maxLength).join("")
+ const wordBoundary = truncated.replace(/\s+\S*$/, "").trim()
+ return Array.from(wordBoundary).length >= maxLength * 0.6
+ ? wordBoundary
+ : truncated.trim()
+}
+
+function compactTerm(value: string): string {
+ return truncateAtWord(value
+ .replace(/^["']|["']$/g, "")
+ .replace(/^\[\[|\]\]$/g, "")
+ .replace(/\s+/g, " ")
+ .trim(), TERM_MAX_LENGTH)
+}
+
+function compactContext(value: string): string {
+ return truncateAtWord(value
+ .replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "")
+ .replace(/[`*_>[\](){}]/g, " ")
+ .replace(/^#{1,6}\s+/gm, "")
+ .replace(/https?:\/\/\S+/gi, " ")
+ .replace(/\s+/g, " ")
+ .trim(), CONTEXT_MAX_LENGTH)
+}
+
+export function groundedFallbackResearchQuery(term: string, context: string): string {
+ const termPart = compactTerm(term)
+ const contextPart = compactContext(context)
+ if (!contextPart) return termPart
+ if (!termPart) return contextPart
+ return truncateAtWord(`${termPart} ${contextPart}`, QUERY_MAX_LENGTH)
+}
+
+export function groundBareResearchQueries(
+ queries: string[],
+ term: string,
+ context: string,
+ bareAliases: string[] = [],
+): string[] {
+ const bareTerms = new Set([term, ...bareAliases]
+ .map(compactTerm)
+ .filter(Boolean)
+ .map((value) => value.toLocaleLowerCase()))
+ const fallback = groundedFallbackResearchQuery(term, context)
+ const grounded = queries.map((query) => {
+ const normalized = query.replace(/\s+/g, " ").trim()
+ const comparisonKey = compactTerm(normalized).toLocaleLowerCase()
+ return normalized && !bareTerms.has(comparisonKey)
+ ? normalized
+ : fallback
+ }).filter(Boolean)
+ const seen = new Set<string>()
+ return grounded.filter((query) => {
+ const key = query.toLocaleLowerCase()
+ if (seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+}
diff --git a/src/lib/review-batch-research.test.ts b/src/lib/review-batch-research.test.ts
index 8fb12f15..21b4ba40 100644
--- a/src/lib/review-batch-research.test.ts
+++ b/src/lib/review-batch-research.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"
import type { ReviewItem } from "@/stores/review-store"
-import { reviewResearchTopic, selectedResearchReviews } from "./review-batch-research"
+import { reviewResearchQueries, reviewResearchTopic, selectedResearchReviews } from "./review-batch-research"
function review(id: string, type: ReviewItem["type"], resolved = false): ReviewItem {
return {
@@ -37,4 +37,27 @@ describe("selectedResearchReviews", () => {
description: "First line\nSecond line",
})).toBe("First line")
})
+
+ it("grounds bare generated queries with the review description", () => {
+ expect(reviewResearchQueries({
+ ...review("a", "suggestion"),
+ title: "AF",
+ description: "attention filter signal in the project pipeline",
+ searchQueries: ["AF", "AF cognitive signal"],
+ })).toEqual([
+ "AF attention filter signal in the project pipeline",
+ "AF cognitive signal",
+ ])
+ })
+
+ it("uses an action-derived topic without reusing queries for the original title", () => {
+ const item = {
+ ...review("a", "suggestion"),
+ title: "Original topic",
+ description: "comparison of two internal mechanisms",
+ searchQueries: undefined,
+ }
+ expect(reviewResearchQueries(item, "X comparison"))
+ .toEqual(["X comparison comparison of two internal mechanisms"])
+ })
})
diff --git a/src/lib/review-batch-research.ts b/src/lib/review-batch-research.ts
index c5469e0c..9a90bc3d 100644
--- a/src/lib/review-batch-research.ts
+++ b/src/lib/review-batch-research.ts
@@ -1,4 +1,5 @@
import type { ReviewItem } from "@/stores/review-store"
+import { groundBareResearchQueries } from "@/lib/research-query-grounding"
const ACTIVE_RESEARCH_STATUSES = new Set([
"queued",
@@ -15,6 +16,15 @@ export function reviewResearchTopic(item: ReviewItem): string {
return item.title.trim() || item.description.split("\n")[0]?.trim() || ""
}
+export function reviewResearchQueries(item: ReviewItem, topic = reviewResearchTopic(item)): string[] {
+ return groundBareResearchQueries(
+ item.searchQueries?.length ? item.searchQueries : [topic],
+ topic,
+ item.description,
+ [item.title],
+ )
+}
+
export function selectedResearchReviews(
items: ReviewItem[],
selectedIds: ReadonlySet<string>,