Skip to content

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

Go

feat(docs): search docs by content for people and agents (MUL-8370) (#10954)

Multica Eve4f7bfd5e2dfd
diff --git a/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx b/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
index 5e9e27324e..d002b19ec1 100644
--- a/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
+++ b/apps/desktop/src/renderer/src/components/desktop-layout.search-workspace.test.tsx
@@ -70,6 +70,8 @@ function payloadFor(path: string, workspace: string): unknown {
if (path === "/api/workspaces") return workspaces;
if (path === "/api/issues/search") return { issues: [issue(workspace === "synthetic-b" ? "b" : "a")] };
if (path === "/api/projects/search" || path === "/api/projects") return { projects: [], total: 0 };
+ if (path === "/api/docs/search") return { docs: [] };
+ if (path === "/api/docs") return { folders: [], docs: [] };
if (path === "/api/issues") return { issues: [], total: 0 };
if (path === "/api/issue-statuses") return { statuses: [] };
if (path === "/api/autopilots") return { autopilots: [], total: 0 };
@@ -207,7 +209,8 @@ it("cancels an in-flight search when the production router switches workspace",
await openSearch();
holdA = true;
fireEvent.change(input(), { target: { value: "alpha" } });
- await waitFor(() => expect(held.length).toBe(2), NETWORK_WAIT);
+ // Issues, projects and docs: one held search request each.
+ await waitFor(() => expect(held.length).toBe(3), NETWORK_WAIT);
await notify("synthetic-b");
await act(async () => {
for (const { response, payload } of held.splice(0)) response.end(JSON.stringify(payload));
diff --git a/e2e/docs.spec.ts b/e2e/docs.spec.ts
index 295c914f99..952de167bb 100644
--- a/e2e/docs.spec.ts
+++ b/e2e/docs.spec.ts
@@ -310,3 +310,19 @@ test("docs link from issues, show up in Cmd+K, and reorganize from the tree", as
expect((await api.getDoc(created)).folder_id).toBe(folder.id);
await page.screenshot({ path: info.outputPath("docs-tree.png"), animations: "disabled", style: "nextjs-portal { display: none; }" });
});
+
+test("Cmd+K finds a doc by words that only appear in its content", async ({ page }) => {
+ const doc = await api.createDoc(
+ "Release runbook",
+ "# Rollout\n\nBefore cutover, rotate the zephyrine credentials and confirm the rollback owner.",
+ );
+ await page.goto(`/${slug}/docs`);
+ await page.getByRole("button", { name: "Search..." }).click();
+ await page.getByRole("combobox", { name: "Command bar" }).fill("zephyrine credentials");
+ const hit = page
+ .getByRole("group", { name: "Docs" })
+ .getByRole("option", { name: /Release runbook/ });
+ await expect(hit).toContainText("rotate the zephyrine credentials");
+ await hit.click();
+ await expect(page).toHaveURL(new RegExp(`/docs/${doc.id}$`));
+});
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 9ad2fda51e..c2d0639a90 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -7,11 +7,13 @@ import {
DocTreeSchema,
DocVersionSchema,
DocVersionListSchema,
+ DocSearchResponseSchema,
} from "../docs/schemas";
import type {
Doc,
DocSummary,
DocFolder,
+ SearchDocsResponse,
DocTree,
DocVersion,
CreateDocRequest,
@@ -932,6 +934,18 @@ export class ApiClient {
{ endpoint: "GET /api/docs" },
);
}
+ // Server-side doc search: titles and Markdown content, ranked title-first.
+ async searchDocs(params: { q: string; limit?: number; offset?: number; signal?: AbortSignal }): Promise<SearchDocsResponse> {
+ const search = new URLSearchParams({ q: params.q });
+ if (params.limit !== undefined) search.set("limit", String(params.limit));
+ if (params.offset !== undefined) search.set("offset", String(params.offset));
+ return parseWithFallback(
+ await this.fetch<unknown>(`/api/docs/search?${search}`, params.signal ? { signal: params.signal } : undefined),
+ DocSearchResponseSchema,
+ { docs: [] },
+ { endpoint: "GET /api/docs/search" },
+ );
+ }
async getDoc(id: string): Promise<Doc> {
return this.parseDoc(
await this.fetch<unknown>(`/api/docs/${id}`),
diff --git a/packages/core/docs/client.test.ts b/packages/core/docs/client.test.ts
index 6439972bd2..3e54625fd6 100644
--- a/packages/core/docs/client.test.ts
+++ b/packages/core/docs/client.test.ts
@@ -100,4 +100,28 @@ describe("knowledge base client", () => {
),
).toBe(false);
});
+
+ it("searches docs and keeps the hits it can read", async () => {
+ const { content: _content, ...summary } = validDoc;
+ const fetchMock = respond({
+ docs: [
+ { ...summary, match_source: "content", matched_snippet: "...rotate the keys..." },
+ { ...summary, id: "d2", match_source: "someday", matched_snippet: null },
+ { id: "", title: 7 },
+ ],
+ });
+ const result = await new ApiClient("https://api.example.test").searchDocs({ q: "rotate keys", limit: 5 });
+ expect(String(fetchMock.mock.calls[0]?.[0])).toBe(
+ "https://api.example.test/api/docs/search?q=rotate+keys&limit=5",
+ );
+ expect(result.docs.map((d) => [d.id, d.matchSource, d.matchedSnippet])).toEqual([
+ ["d1", "content", "...rotate the keys..."],
+ ["d2", "content", null],
+ ]);
+ });
+
+ it("falls back to no hits when the search response is malformed", async () => {
+ respond({ results: "nope" });
+ expect(await new ApiClient("https://api.example.test").searchDocs({ q: "x" })).toEqual({ docs: [] });
+ });
});
diff --git a/packages/core/docs/schemas.ts b/packages/core/docs/schemas.ts
index 4d886a4ae0..66e2a4f280 100644
--- a/packages/core/docs/schemas.ts
+++ b/packages/core/docs/schemas.ts
@@ -60,6 +60,27 @@ export const DocTreeSchema = z.object({
folders: z.array(DocFolderSchema),
docs: z.array(DocSummarySchema),
});
+// One unparseable hit is dropped instead of emptying the whole result list.
+const searchHit = summary
+ .extend({
+ match_source: z.enum(["title", "content"]).catch("content"),
+ matched_snippet: z.string().nullable().optional(),
+ })
+ .transform((d) => ({
+ ...mapSummary(d),
+ matchSource: d.match_source,
+ matchedSnippet: d.matched_snippet ?? null,
+ }));
+export const DocSearchResponseSchema = z.object({
+ docs: z
+ .array(z.unknown())
+ .transform((rows) =>
+ rows.flatMap((row) => {
+ const hit = searchHit.safeParse(row);
+ return hit.success ? [hit.data] : [];
+ }),
+ ),
+});
export const DocVersionSchema = z
.object({
doc_id: z.string(),
diff --git a/packages/core/search-index/index.ts b/packages/core/search-index/index.ts
index 0b6d49076e..81bdf1a26d 100644
--- a/packages/core/search-index/index.ts
+++ b/packages/core/search-index/index.ts
@@ -2,6 +2,7 @@ export {
forgetLocalSearchIndex,
getLocalSearchIndex,
isLocalSearchReady,
+ searchDocs,
searchIssues,
searchProjects,
wipeLocalSearchIndex,
diff --git a/packages/core/search-index/instance.ts b/packages/core/search-index/instance.ts
index 190c410eb9..621e633278 100644
--- a/packages/core/search-index/instance.ts
+++ b/packages/core/search-index/instance.ts
@@ -1,5 +1,5 @@
import { api } from "../api";
-import type { SearchIssuesResponse, SearchProjectsResponse } from "../types";
+import type { SearchDocsResponse, SearchIssuesResponse, SearchProjectsResponse } from "../types";
import { LocalSearchIndexClient, startSearchIndexWorker } from "./client";
let client: LocalSearchIndexClient | null = null;
@@ -27,6 +27,15 @@ export async function searchProjects(params: Parameters<typeof api.searchProject
return local ?? api.searchProjects(params);
}
+/**
+ * Doc search. The local index does not hold docs yet, so the server always
+ * answers; callers go through here so docs join the local-first path in one
+ * place when it does.
+ */
+export async function searchDocs(params: Parameters<typeof api.searchDocs>[0]): Promise<SearchDocsResponse> {
+ return api.searchDocs(params);
+}
+
/** Whether searches in this tab are currently answered locally. */
export function isLocalSearchReady(): boolean {
return getLocalSearchIndex().isServing();
diff --git a/packages/core/types/doc.ts b/packages/core/types/doc.ts
index c0e8f469f7..43bef6e796 100644
--- a/packages/core/types/doc.ts
+++ b/packages/core/types/doc.ts
@@ -13,6 +13,14 @@ export interface DocSummary {
createdAt: string;
updatedAt: string;
}
+/** A doc search hit: where the query matched, with an excerpt for content hits. */
+export interface SearchDocResult extends DocSummary {
+ matchSource: "title" | "content";
+ matchedSnippet: string | null;
+}
+export interface SearchDocsResponse {
+ docs: SearchDocResult[];
+}
export interface Doc extends DocSummary {
content: string;
}
diff --git a/packages/views/locales/en/search.json b/packages/views/locales/en/search.json
index febed677b8..efe41afeb9 100644
--- a/packages/views/locales/en/search.json
+++ b/packages/views/locales/en/search.json
@@ -164,5 +164,6 @@
},
"trigger": {
"label": "Search..."
- }
+ },
+ "untitled_doc": "Untitled"
}
diff --git a/packages/views/locales/es/search.json b/packages/views/locales/es/search.json
index 22cfcbf179..19b9ad2dcb 100644
--- a/packages/views/locales/es/search.json
+++ b/packages/views/locales/es/search.json
@@ -164,5 +164,6 @@
"prefix_commands": "Comandos",
"prefix_issues": "Tareas",
"prefix_people": "Personas y agentes"
- }
+ },
+ "untitled_doc": "Sin título"
}
diff --git a/packages/views/locales/fr/search.json b/packages/views/locales/fr/search.json
index eb39bdd806..8016e28476 100644
--- a/packages/views/locales/fr/search.json
+++ b/packages/views/locales/fr/search.json
@@ -164,5 +164,6 @@
},
"trigger": {
"label": "Rechercher..."
- }
+ },
+ "untitled_doc": "Sans titre"
}
diff --git a/packages/views/locales/ja/search.json b/packages/views/locales/ja/search.json
index f248b29677..08a804fe88 100644
--- a/packages/views/locales/ja/search.json
+++ b/packages/views/locales/ja/search.json
@@ -161,5 +161,6 @@
},
"trigger": {
"label": "検索..."
- }
+ },
+ "untitled_doc": "無題"
}
diff --git a/packages/views/locales/ko/search.json b/packages/views/locales/ko/search.json
index 281421f7f5..6d00b58bdf 100644
--- a/packages/views/locales/ko/search.json
+++ b/packages/views/locales/ko/search.json
@@ -161,5 +161,6 @@
},
"trigger": {
"label": "검색..."
- }
+ },
+ "untitled_doc": "제목 없음"
}
diff --git a/packages/views/locales/ru/search.json b/packages/views/locales/ru/search.json
index d675918f68..5eb56d51a8 100644
--- a/packages/views/locales/ru/search.json
+++ b/packages/views/locales/ru/search.json
@@ -170,5 +170,6 @@
},
"trigger": {
"label": "Поиск..."
- }
+ },
+ "untitled_doc": "Без названия"
}
diff --git a/packages/views/locales/zh-Hans/search.json b/packages/views/locales/zh-Hans/search.json
index 85898e85e5..0e3c45aa0f 100644
--- a/packages/views/locales/zh-Hans/search.json
+++ b/packages/views/locales/zh-Hans/search.json
@@ -161,5 +161,6 @@
},
"trigger": {
"label": "搜索..."
- }
+ },
+ "untitled_doc": "未命名"
}
diff --git a/packages/views/locales/zh-Hant/search.json b/packages/views/locales/zh-Hant/search.json
index 4fb0852c0d..ed05c48f96 100644
--- a/packages/views/locales/zh-Hant/search.json
+++ b/packages/views/locales/zh-Hant/search.json
@@ -161,5 +161,6 @@
},
"trigger": {
"label": "搜尋..."
- }
+ },
+ "untitled_doc": "未命名"
}
diff --git a/packages/views/search/root-view.tsx b/packages/views/search/root-view.tsx
index b2644e90c6..b4af757b5a 100644
--- a/packages/views/search/root-view.tsx
+++ b/packages/views/search/root-view.tsx
@@ -21,6 +21,7 @@ import { ProjectIcon } from "../projects/components/project-icon";
import { WorkspaceAvatar } from "../workspace/workspace-avatar";
import { useT } from "../i18n";
import { HighlightText } from "./highlight-text";
+import { stripMentionMarkdown } from "../issues/utils/strip-mention-markdown";
import { useIssueTargetWriter } from "./issue-target";
import { usePalette } from "./palette-context";
import { CommandGroupView, CommandRow, PaletteGroup, ROW_CLASS, ROW_ICON_CLASS, RowHint } from "./rows";
@@ -349,14 +350,15 @@ export function RootView({ model, rawQuery }: { model: RootModel; rawQuery: stri
score: objects.docs[0]!.score,
node: (
<PaletteGroup key="docs" heading={t(($) => $.groups.docs)}>
- {objects.docs.map(({ item: { doc, folder } }) => (
+ {objects.docs.map(({ item: { doc, folder, snippet } }) => (
<ObjectRow
key={doc.id}
value={`doc:${doc.id}`}
icon={<FileText className={ROW_ICON_CLASS} />}
- title={doc.title}
+ title={doc.title || t(($) => $.untitled_doc)}
query={query}
- detail={folder ?? undefined}
+ // A content hit says why it matched; a title hit says where it lives.
+ detail={snippet ? stripMentionMarkdown(snippet) : (folder ?? undefined)}
onSelect={() => palette.navigate(p.docDetail(doc.id))}
/>
))}
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsx
index 983cdad73a..96c19890d1 100644
--- a/packages/views/search/search-command.test.tsx
+++ b/packages/views/search/search-command.test.tsx
@@ -371,6 +371,7 @@ describe("SearchCommand", () => {
apiFns.set("getBaseUrl", vi.fn(() => "http://127.0.0.1:8080"));
apiFns.set("searchIssues", vi.fn(() => Promise.resolve({ issues: [], total: 0 })));
apiFns.set("searchProjects", vi.fn(() => Promise.resolve({ projects: [], total: 0 })));
+ apiFns.set("searchDocs", vi.fn(() => Promise.resolve({ docs: [] })));
mockPush.mockReset();
mockPathname.current = "/ws-test/issues";
mockGetShareableUrl.mockReset().mockImplementation((p: string) => `https://app.multica/${p}`);
@@ -713,6 +714,38 @@ describe("SearchCommand", () => {
expect(mockPush).toHaveBeenCalledWith("/ws-test/docs/doc-runbook");
});
+ it("adds server content hits under Docs with an excerpt, without repeating title hits", async () => {
+ seed(docTreeOptions("ws-test"), {
+ folders: [{ id: "folder-eng", title: "Engineering" }],
+ docs: [{ id: "doc-rotation", title: "Key rotation", folderId: "folder-eng" }],
+ });
+ const summary = (id: string, title: string) => ({
+ id, workspaceId: "ws-test", folderId: "folder-eng", title, revision: 1, versionCount: 1,
+ createdByType: "member", createdById: ME, updatedByType: "member", updatedById: ME,
+ createdAt: "2026-11-19T00:00:00Z", updatedAt: "2026-11-19T00:00:00Z",
+ });
+ api("searchDocs").mockResolvedValue({
+ docs: [
+ { ...summary("doc-rotation", "Key rotation"), matchSource: "title", matchedSnippet: null },
+ {
+ ...summary("doc-runbook", "Release runbook"),
+ matchSource: "content",
+ matchedSnippet: "...before cutover, follow [Key rotation](mention://doc/doc-rotation) steps...",
+ },
+ ],
+ });
+ const user = userEvent.setup();
+ renderSearch();
+ await user.type(input(), "rotation");
+
+ const docs = await screen.findByRole("group", { name: "Docs" });
+ await waitFor(() => expect(within(docs).getAllByRole("option")).toHaveLength(2));
+ const rows = within(docs).getAllByRole("option");
+ expect(rows[0]).toHaveTextContent("Key rotationEngineering");
+ expect(rows[1]).toHaveTextContent("Release runbook...before cutover, follow Key rotation steps...");
+ expect(api("searchDocs")).toHaveBeenCalledWith(expect.objectContaining({ q: "rotation", limit: 10 }));
+ });
+
it("lists workspace members and navigates to the member page", async () => {
const user = userEvent.setup();
seed(memberListOptions("ws-test"), [
diff --git a/packages/views/search/use-doc-search.test.tsx b/packages/views/search/use-doc-search.test.tsx
new file mode 100644
index 0000000000..3970d1399e
--- /dev/null
+++ b/packages/views/search/use-doc-search.test.tsx
@@ -0,0 +1,64 @@
+import { act, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const index = vi.hoisted(() => ({
+ isLocalSearchReady: vi.fn(() => true),
+ searchIssues: vi.fn(),
+ searchProjects: vi.fn(),
+ searchDocs: vi.fn(),
+}));
+vi.mock("@multica/core/search-index", () => index);
+
+import { DOC_SEARCH_DEBOUNCE_MS, useDocSearch } from "./use-doc-search";
+import { useServerSearch } from "./use-server-search";
+
+const issue = { id: "i1", identifier: "MUL-1", title: "Rotate keys" };
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ index.isLocalSearchReady.mockReturnValue(true);
+ index.searchIssues.mockResolvedValue({ issues: [issue], total: 1 });
+ index.searchProjects.mockResolvedValue({ projects: [], total: 0 });
+});
+afterEach(() => vi.useRealTimers());
+
+describe("palette doc search", () => {
+ it("shows local issue results without waiting for a doc search that never returns", async () => {
+ index.searchDocs.mockReturnValue(new Promise(() => {}));
+ const { result } = renderHook(({ q }) => ({ server: useServerSearch(q, { projects: true }), docs: useDocSearch(q, true) }), {
+ initialProps: { q: "rot" },
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(DOC_SEARCH_DEBOUNCE_MS + 50);
+ });
+ expect(result.current.server.results).toMatchObject({ query: "rot", issues: [issue] });
+ expect(result.current.server.stale).toBe(false);
+ expect(result.current.docs.docs).toEqual([]);
+ });
+
+ it("sends one doc request for a burst of keystrokes, for the final query", async () => {
+ index.searchDocs.mockResolvedValue({ docs: [{ id: "d1", title: "Runbook" }] });
+ const { result, rerender } = renderHook(({ q }) => useDocSearch(q, true), { initialProps: { q: "r" } });
+ for (const q of ["ro", "rot", "rota"]) {
+ rerender({ q });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(50);
+ });
+ }
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(DOC_SEARCH_DEBOUNCE_MS);
+ });
+ expect(index.searchDocs).toHaveBeenCalledTimes(1);
+ expect(index.searchDocs).toHaveBeenCalledWith(expect.objectContaining({ q: "rota", limit: 10 }));
+ expect(result.current).toEqual({ query: "rota", docs: [{ id: "d1", title: "Runbook" }] });
+ });
+
+ it("does not search docs in a scoped search", async () => {
+ renderHook(() => useDocSearch("rota", false));
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(DOC_SEARCH_DEBOUNCE_MS * 2);
+ });
+ expect(index.searchDocs).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/views/search/use-doc-search.ts b/packages/views/search/use-doc-search.ts
new file mode 100644
index 0000000000..554fc772cf
--- /dev/null
+++ b/packages/views/search/use-doc-search.ts
@@ -0,0 +1,49 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import type { SearchDocResult } from "@multica/core/types";
+import { searchDocs } from "@multica/core/search-index";
+
+/** Doc hits from the server, with the query they answer. */
+export interface DocSearchResults {
+ query: string;
+ docs: SearchDocResult[];
+}
+
+const NO_DOCS: DocSearchResults = { query: "", docs: [] };
+/**
+ * Doc search always goes to the server (the local index does not hold docs),
+ * so it keeps its own debounce even when issue search answers locally on every
+ * keystroke, and its own request so it never holds back those rows.
+ */
+export const DOC_SEARCH_DEBOUNCE_MS = 300;
+
+/** Server doc search for the palette. An empty or disabled query clears it. */
+export function useDocSearch(query: string, enabled: boolean): DocSearchResults {
+ const [results, setResults] = useState<DocSearchResults>(NO_DOCS);
+ const q = enabled ? query.trim() : "";
+
+ useEffect(() => {
+ if (!q) {
+ setResults(NO_DOCS);
+ return;
+ }
+ const controller = new AbortController();
+ const timer = setTimeout(() => {
+ searchDocs({ q, limit: 10, signal: controller.signal }).then(
+ (res) => {
+ if (!controller.signal.aborted) setResults({ query: q, docs: res.docs });
+ },
+ () => {
+ if (!controller.signal.aborted) setResults({ query: q, docs: [] });
+ },
+ );
+ }, DOC_SEARCH_DEBOUNCE_MS);
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ }, [q]);
+
+ return results;
+}
diff --git a/packages/views/search/use-object-search.ts b/packages/views/search/use-object-search.ts
index 783fde582b..44dc2cb36f 100644
--- a/packages/views/search/use-object-search.ts
+++ b/packages/views/search/use-object-search.ts
@@ -48,6 +48,8 @@ export interface ObjectHits {
export interface PaletteDoc {
doc: DocSummary;
folder: string | null;
+ /** Excerpt around a content match, from server search. */
+ snippet?: string;
}
const EMPTY_AUTOPILOTS: Autopilot[] = [];
@@ -93,7 +95,10 @@ function viewScore(view: PaletteView, query: string): number {
* the palette does not otherwise need (views, autopilots, chats, skills) load
* only once the user types.
*/
-export function useObjectSearch(query: string, open: boolean): ObjectHits & { directory: ReturnType<typeof useActorDirectory> } {
+export function useObjectSearch(
+ query: string,
+ open: boolean,
+): ObjectHits & { directory: ReturnType<typeof useActorDirectory>; docFolders: ReadonlyMap<string, string> } {
const wsId = useWorkspaceId();
const directory = useActorDirectory(open);
const typing = open && query.length > 0;
@@ -103,12 +108,13 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { di
const { data: chats = EMPTY_CHATS } = useQuery({ ...chatSessionsOptions(wsId), enabled: typing });
const { data: skills = EMPTY_SKILLS } = useQuery({ ...skillListOptions(wsId), enabled: typing });
const { data: docTree = EMPTY_DOC_TREE } = useQuery({ ...docTreeOptions(wsId), enabled: typing && !!wsId });
+ const docFolders = useMemo(() => new Map(docTree.folders.map((f) => [f.id, f.title])), [docTree]);
const docs = useMemo<PaletteDoc[]>(() => {
- const folders = new Map(docTree.folders.map((f) => [f.id, f.title]));
+ const folders = docFolders;
return docTree.docs
.filter((doc) => doc.title.trim() !== "")
.map((doc) => ({ doc, folder: doc.folderId ? (folders.get(doc.folderId) ?? null) : null }));
- }, [docTree]);
+ }, [docFolders, docTree]);
// Account-level cache entry the sidebar's workspace switcher already
// holds, so the Workspaces group adds no request of its own.
const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());
@@ -153,5 +159,5 @@ export function useObjectSearch(query: string, open: boolean): ObjectHits & { di
};
}, [autopilots, chats, directory, docs, query, skills, views, workspaces, wsId]);
- return { ...hits, directory };
+ return { ...hits, directory, docFolders };
}
diff --git a/packages/views/search/use-root-model.ts b/packages/views/search/use-root-model.ts
index 0abe608f64..2d1284f684 100644
--- a/packages/views/search/use-root-model.ts
+++ b/packages/views/search/use-root-model.ts
@@ -4,7 +4,7 @@ import { useMemo } from "react";
import type { CommandBarContext } from "@multica/core/command-bar";
import { WORKSPACE_PAGES, type WorkspacePageKey } from "@multica/core/paths";
import { partitionAggregatedSearchResults } from "@multica/core/search/cancelled-rank";
-import type { SearchIssueResult, SearchProjectResult } from "@multica/core/types";
+import type { SearchDocResult, SearchIssueResult, SearchProjectResult } from "@multica/core/types";
import { useT } from "../i18n";
import { useAgentCommandGroup, useAutopilotCommandGroup, useChatCommandGroup, useInboxCommandGroup, useProjectCommandGroup } from "./commands/context-commands";
import { useGlobalCommands } from "./commands/global-commands";
@@ -12,9 +12,10 @@ import { useIssueCommandGroup } from "./commands/issue-commands";
import { parseScope, scoreRow, scoreText, type SearchScope } from "./matching";
import type { IssueTarget, PaletteCommand, PaletteCommandGroup } from "./types";
import type { AgentEntry } from "./use-actor-directory";
-import { useObjectSearch, type ObjectHits, type Scored } from "./use-object-search";
+import { useObjectSearch, type ObjectHits, type PaletteDoc, type Scored } from "./use-object-search";
import { useRecentItems, type RecentItem } from "./use-recent-items";
import { useServerSearch, type SearchResults } from "./use-server-search";
+import { useDocSearch } from "./use-doc-search";
// The palette's Pages group is generated from WORKSPACE_PAGES, the same
// registry the sidebar nav and the desktop tab bar read. It used to be a
@@ -104,6 +105,37 @@ export function issueScore(issue: SearchIssueResult, q: string): number {
return Math.max(scoreText(issue.title, q), SERVER_ONLY_SCORE);
}
+/**
+ * Title hits from the cached doc tree answer on every keystroke; the server
+ * adds what only it can find, content matches with an excerpt. A doc found
+ * both ways keeps its instant row, picking up the server's excerpt if any.
+ */
+export function mergeDocHits(
+ local: Scored<PaletteDoc>[],
+ server: SearchDocResult[],
+ folders: ReadonlyMap<string, string>,
+ q: string,
+): Scored<PaletteDoc>[] {
+ const fromServer = new Map(server.map((doc) => [doc.id, doc]));
+ const merged = local.map((hit) => {
+ const snippet = fromServer.get(hit.item.doc.id)?.matchedSnippet;
+ return snippet ? { ...hit, item: { ...hit.item, snippet } } : hit;
+ });
+ const listed = new Set(local.map((hit) => hit.item.doc.id));
+ for (const doc of server) {
+ if (listed.has(doc.id)) continue;
+ merged.push({
+ item: {
+ doc,
+ folder: doc.folderId ? (folders.get(doc.folderId) ?? null) : null,
+ ...(doc.matchedSnippet ? { snippet: doc.matchedSnippet } : {}),
+ },
+ score: Math.max(scoreText(doc.title, q), SERVER_ONLY_SCORE),
+ });
+ }
+ return merged;
+}
+
export function projectScore(project: SearchProjectResult, q: string): number {
return Math.max(scoreText(project.title, q), SERVER_ONLY_SCORE);
}
@@ -151,6 +183,7 @@ export function useRootModel(
const searching = active && scope !== "commands" && scope !== "people" ? text : "";
const server = useServerSearch(searching, { projects: scope === "all" });
+ const docSearch = useDocSearch(searching, scope === "all");
const objects = useObjectSearch(scope === "issues" || scope === "commands" ? "" : q, active);
const recent = useRecentItems(active && !rawQuery.trim());
@@ -234,7 +267,17 @@ export function useRootModel(
autopilots: scope === "all" ? objects.autopilots : [],
chats: scope === "all" ? objects.chats : [],
skills: scope === "all" ? objects.skills : [],
- docs: scope === "all" ? objects.docs : [],
+ // Server doc rows answering an earlier query are dropped rather than
+ // shown stale; the instant title hits cover the gap until they land.
+ docs:
+ scope === "all"
+ ? mergeDocHits(
+ objects.docs,
+ docSearch.query === searching.trim() ? docSearch.docs : [],
+ objects.docFolders,
+ q,
+ )
+ : [],
workspaces: scope === "all" ? objects.workspaces : [],
};
@@ -318,6 +361,7 @@ export function useRootModel(
batchTarget,
chatGroup,
contexts,
+ docSearch,
globalCommands,
inboxGroup,
issueContext,
@@ -328,6 +372,7 @@ export function useRootModel(
q,
recent,
scope,
+ searching,
server,
singleGroup,
singleTarget,
diff --git a/server/cmd/multica/cmd_doc.go b/server/cmd/multica/cmd_doc.go
index 82c0b78cf1..87203f854c 100644
--- a/server/cmd/multica/cmd_doc.go
+++ b/server/cmd/multica/cmd_doc.go
@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
+ "net/url"
"os"
"sort"
"strings"
@@ -35,6 +36,19 @@ var docListCmd = &cobra.Command{
RunE: runDocList,
}
+var docSearchCmd = &cobra.Command{
+ Use: "search <query>",
+ Short: "Search docs by title or content",
+ Long: "Search docs in the current workspace. The query matches doc titles and\n" +
+ "Markdown content; with several words, every word must appear somewhere\n" +
+ "in the doc. Title matches rank first.\n\n" +
+ "The MATCH column (match_source in --output json) reports whether the\n" +
+ "title or the content matched, with a short excerpt for content hits.\n" +
+ "Read a result with `multica doc get <doc-id>`.",
+ Args: exactArgs(1),
+ RunE: runDocSearch,
+}
+
var docGetCmd = &cobra.Command{
Use: "get <doc-id>",
Short: "Get a doc with its content and current revision",
@@ -56,8 +70,10 @@ var docUpdateCmd = &cobra.Command{
}
func init() {
- docCmd.AddCommand(docListCmd, docGetCmd, docCreateCmd, docUpdateCmd)
+ docCmd.AddCommand(docListCmd, docSearchCmd, docGetCmd, docCreateCmd, docUpdateCmd)
docListCmd.Flags().String("output", "table", "Output format: table or json")
+ docSearchCmd.Flags().Int("limit", 20, "Maximum results (at most 50)")
+ docSearchCmd.Flags().String("output", "table", "Output format: table or json")
docGetCmd.Flags().String("output", "json", "Output format: json or content")
for _, cmd := range []*cobra.Command{docCreateCmd, docUpdateCmd} {
cmd.Flags().String("title", "", "Document title")
@@ -212,6 +228,50 @@ func runDocList(cmd *cobra.Command, _ []string) error {
return nil
}
+func runDocSearch(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ params := url.Values{}
+ params.Set("q", args[0])
+ if v, _ := cmd.Flags().GetInt("limit"); v > 0 {
+ params.Set("limit", fmt.Sprintf("%d", v))
+ }
+ var result map[string]any
+ if err := client.GetJSON(ctx, "/api/docs/search?"+params.Encode(), &result); err != nil {
+ return fmt.Errorf("search docs: %w", err)
+ }
+ if output, _ := cmd.Flags().GetString("output"); output == "json" {
+ return cli.PrintJSON(os.Stdout, result)
+ }
+ docs, _ := result["docs"].([]any)
+ rows := make([][]string, 0, len(docs))
+ for _, raw := range docs {
+ doc, ok := raw.(map[string]any)
+ if !ok {
+ continue
+ }
+ match := strVal(doc, "match_source")
+ if snippet := strVal(doc, "matched_snippet"); snippet != "" {
+ if runes := []rune(snippet); len(runes) > 60 {
+ snippet = string(runes[:57]) + "..."
+ }
+ match += ": " + snippet
+ }
+ updated := strVal(doc, "updated_at")
+ if len(updated) >= 10 {
+ updated = updated[:10]
+ }
+ rows = append(rows, []string{strVal(doc, "id"), strVal(doc, "title"), updated, match})
+ }
+ cli.PrintTable(os.Stdout, []string{"ID", "TITLE", "UPDATED", "MATCH"}, rows)
+ return nil
+}
+
func runDocGet(cmd *cobra.Command, args []string) error {
client, err := newAPIClient(cmd)
if err != nil {
diff --git a/server/cmd/multica/cmd_doc_test.go b/server/cmd/multica/cmd_doc_test.go
index 63dd3bd78f..a855bc3193 100644
--- a/server/cmd/multica/cmd_doc_test.go
+++ b/server/cmd/multica/cmd_doc_test.go
@@ -1,8 +1,11 @@
package main
import (
+ "encoding/json"
"errors"
"net/http"
+ "net/http/httptest"
+ "net/url"
"strings"
"testing"
@@ -10,7 +13,7 @@ import (
)
func TestDocCommandsExposeOnlyAgentReadWrite(t *testing.T) {
- expected := map[string]bool{"list": true, "get": true, "create": true, "update": true}
+ expected := map[string]bool{"list": true, "search": true, "get": true, "create": true, "update": true}
for _, command := range docCmd.Commands() {
if !expected[command.Name()] {
t.Fatalf("unexpected doc command: %s", command.Name())
@@ -32,3 +35,34 @@ func TestDocConflictErrorExplainsRecovery(t *testing.T) {
t.Fatal("lost underlying error")
}
}
+
+func TestRunDocSearchQueriesServerSearch(t *testing.T) {
+ var gotPath string
+ var gotQuery url.Values
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ gotPath, gotQuery = r.URL.Path, r.URL.Query()
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{"docs": []any{map[string]any{
+ "id": "doc-1", "title": "Release runbook", "updated_at": "2026-11-19T00:00:00Z",
+ "match_source": "content", "matched_snippet": "...rotate the credentials before cutover...",
+ }}})
+ }))
+ 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 := docSearchCmd
+ _ = cmd.Flags().Set("limit", "5")
+ t.Cleanup(func() { _ = cmd.Flags().Set("limit", "20") })
+ out, err := captureStdout(t, func() error { return runDocSearch(cmd, []string{"rotate credentials"}) })
+ if err != nil {
+ t.Fatalf("runDocSearch: %v", err)
+ }
+ if gotPath != "/api/docs/search" || gotQuery.Get("q") != "rotate credentials" || gotQuery.Get("limit") != "5" {
+ t.Fatalf("request = %s?%s", gotPath, gotQuery.Encode())
+ }
+ if !strings.Contains(out, "doc-1") || !strings.Contains(out, "content: ...rotate the credentials") {
+ t.Fatalf("table output missing the hit: %q", out)
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9a21c8912b..417c410029 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2333,6 +2333,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Route("/api/docs", func(r chi.Router) {
r.Get("/", h.ListDocTree)
r.Post("/", h.CreateDoc)
+ r.Get("/search", h.SearchDocs)
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetDoc)
r.Patch("/", h.UpdateDoc)
diff --git a/server/internal/daemon/execenv/runtime_config_sections.go b/server/internal/daemon/execenv/runtime_config_sections.go
index 87ebb570b4..d33a1813e7 100644
--- a/server/internal/daemon/execenv/runtime_config_sections.go
+++ b/server/internal/daemon/execenv/runtime_config_sections.go
@@ -277,7 +277,7 @@ func writeAvailableCommands(b *strings.Builder, ctx TaskContextForEnv) {
b.WriteString(duplicateOfCommandLine)
b.WriteString("- `multica issue wakeup <create|list|get|update|disable|trigger|delete|runs|events>` — persist an event, condition or time wakeup on this issue, then finish the current run. When the platform can check the fact itself, use one `--until-*` condition so no run starts before it holds; check the rule's `last_error` for missing PR links or snapshots, which are retried automatically. Conditions, PR rules and actor filters: `multica issue wakeup create --help` and the multica-platform issues reference.\n")
b.WriteString("- `multica issue children <id> [--output json]` — list a parent's sub-issues grouped by stage.\n")
- b.WriteString("- `multica doc list|get|create|update` — workspace docs; `doc update` needs `--base-revision` from `multica doc get` (details: `multica doc --help`).\n")
+ b.WriteString("- `multica doc list|search|get|create|update` — workspace docs; `doc search <query>` matches titles and content; `doc update` needs `--base-revision` from `multica doc get` (details: `multica doc --help`).\n")
b.WriteString("- `multica issue comment add <issue-id> [--content \"...\" | --content-file <path> | --content-stdin] [--parent <comment-id>] [--attachment <path>]` — post a comment. Agent-authored bodies MUST use `--content-file` with a file inside your working directory; full flags: `multica issue comment add --help`.\n")
b.WriteString("- `multica repo checkout <url> [--ref <branch-or-sha>] [--fresh]` — repository checkout on a dedicated branch; re-running it keeps a checkout that has uncommitted or unpushed work, or is already on this task's branch, and only fetches; a clean, fully pushed checkout on another branch starts over on a new branch. `--fresh` discards uncommitted and untracked files for a new branch; commits stay on the old branch, so push any you still need first.\n\n")
b.WriteString("Commits use the user's configured Git identity; keep it unless asked. For a requested override in a managed checkout use `git config --worktree user.name` / `user.email` — plain or `--local` config can leak into a shared cache; never change the global identity.\n\n")
diff --git a/server/internal/handler/doc_search.go b/server/internal/handler/doc_search.go
new file mode 100644
index 0000000000..c44e8bfc7e
--- /dev/null
+++ b/server/internal/handler/doc_search.go
@@ -0,0 +1,200 @@
+package handler
+
+import (
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strconv"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+// Doc search follows the same contract as issue and project search: a
+// substring match on the lowered phrase or on every whitespace-separated term,
+// ranked title hits first, run under the shared search timeout. It is the
+// server answer clients fall back to, and the one agents use through
+// `multica doc search`.
+
+const (
+ docSearchDefaultLimit = 20
+ docSearchMaxLimit = 50
+ // Runes of content returned around the first hit. Docs can hold 2 MB of
+ // Markdown; the snippet is cut from this window, never from the whole body.
+ docSearchWindowBefore = 200
+ docSearchWindowLength = 600
+)
+
+// SearchDocResponse is a doc summary plus where the query matched.
+type SearchDocResponse struct {
+ DocSummaryResponse
+ // "title" or "content": the strongest field that matched.
+ MatchSource string `json:"match_source"`
+ // A short excerpt around the match, for content hits only.
+ MatchedSnippet *string `json:"matched_snippet,omitempty"`
+}
+
+// buildDocSearchQuery builds the doc search SQL. Placeholders the caller
+// fills: the workspace id at args[1], limit and offset as the last two.
+func buildDocSearchQuery(phrase string, terms []string) (string, []any) {
+ phrase = strings.ToLower(phrase)
+ lowered := make([]string, len(terms))
+ for i, t := range terms {
+ lowered[i] = strings.ToLower(t)
+ }
+
+ argIdx := 1
+ args := []any{}
+ nextArg := func(val any) string {
+ args = append(args, val)
+ s := fmt.Sprintf("$%d", argIdx)
+ argIdx++
+ return s
+ }
+
+ phraseParam := nextArg(escapeLike(phrase))
+ wsParam := nextArg(nil)
+ contains := func(p string) string { return "'%' || " + p + " || '%'" }
+ title := "LOWER(d.title)"
+ content := "LOWER(d.content)"
+
+ var termParams []string
+ if len(lowered) > 1 {
+ for _, t := range lowered {
+ termParams = append(termParams, nextArg(escapeLike(t)))
+ }
+ }
+
+ where := fmt.Sprintf("(%s LIKE %s OR %s LIKE %s)", title, contains(phraseParam), content, contains(phraseParam))
+ allTermsInTitle := ""
+ if len(termParams) > 1 {
+ var each, inTitle []string
+ for _, tp := range termParams {
+ each = append(each, fmt.Sprintf("(%s LIKE %s OR %s LIKE %s)", title, contains(tp), content, contains(tp)))
+ inTitle = append(inTitle, fmt.Sprintf("%s LIKE %s", title, contains(tp)))
+ }
+ where = "(" + where + " OR (" + strings.Join(each, " AND ") + "))"
+ allTermsInTitle = "(" + strings.Join(inTitle, " AND ") + ")"
+ }
+
+ // strpos and the exact-title tier take the raw (unescaped) phrase; LIKE
+ // takes the escaped one, so a title with % or _ still ranks as exact.
+ rawPhrase := nextArg(phrase)
+ rankCases := []string{
+ fmt.Sprintf("WHEN %s = %s THEN 0", title, rawPhrase),
+ fmt.Sprintf("WHEN %s LIKE %s || '%%' THEN 1", title, phraseParam),
+ fmt.Sprintf("WHEN %s LIKE %s THEN 2", title, contains(phraseParam)),
+ }
+ matchSource := fmt.Sprintf("WHEN %s LIKE %s THEN 'title'", title, contains(phraseParam))
+ if allTermsInTitle != "" {
+ rankCases = append(rankCases, fmt.Sprintf("WHEN %s THEN 3", allTermsInTitle))
+ matchSource += fmt.Sprintf(" WHEN %s THEN 'title'", allTermsInTitle)
+ }
+ rankCases = append(rankCases, fmt.Sprintf("WHEN %s LIKE %s THEN 4", content, contains(phraseParam)))
+ rank := "CASE " + strings.Join(rankCases, " ") + " ELSE 5 END"
+
+ // A multi-term content hit anchors on the first term; the Go snippet then
+ // centers on the earliest.
+ anchor := rawPhrase
+ if len(lowered) > 1 {
+ anchor = nextArg(lowered[0])
+ }
+ window := fmt.Sprintf(
+ `substring(d.content from greatest(
+ CASE WHEN strpos(%[1]s, %[2]s) > 0 THEN strpos(%[1]s, %[2]s) ELSE strpos(%[1]s, %[3]s) END - %[4]d, 1
+ ) for %[5]d)`,
+ content, rawPhrase, anchor, docSearchWindowBefore, docSearchWindowLength,
+ )
+
+ limitParam := nextArg(nil)
+ offsetParam := nextArg(nil)
+ query := fmt.Sprintf(`SELECT d.id, d.workspace_id, d.folder_id, d.title, d.revision, d.version_count,
+ d.created_by_type, d.created_by_id, d.updated_by_type, d.updated_by_id, d.created_at, d.updated_at,
+ CASE %s ELSE 'content' END AS match_source,
+ %s AS content_window
+ FROM doc d
+ WHERE d.workspace_id = %s AND %s
+ ORDER BY %s, d.updated_at DESC
+ LIMIT %s OFFSET %s`,
+ matchSource, window, wsParam, where, rank, limitParam, offsetParam)
+ return query, args
+}
+
+func (h *Handler) SearchDocs(w http.ResponseWriter, r *http.Request) {
+ _, wsUUID, workspaceID, ok := h.docWorkspace(w, r)
+ if !ok {
+ return
+ }
+ ctx := r.Context()
+ q := strings.TrimSpace(r.URL.Query().Get("q"))
+ if q == "" {
+ writeError(w, http.StatusBadRequest, "q parameter is required")
+ return
+ }
+ limit := docSearchDefaultLimit
+ if v, err := strconv.Atoi(r.URL.Query().Get("limit")); err == nil && v > 0 {
+ limit = min(v, docSearchMaxLimit)
+ }
+ offset := 0
+ if v, err := strconv.Atoi(r.URL.Query().Get("offset")); err == nil && v >= 0 {
+ offset = v
+ }
+
+ sqlQuery, args := buildDocSearchQuery(q, splitSearchTerms(q))
+ args[1] = wsUUID
+ args[len(args)-2] = limit
+ args[len(args)-1] = offset
+
+ resp := []SearchDocResponse{}
+ err := runSearchQuery(ctx, h.TxStarter, sqlQuery, args, func(rows pgx.Rows) error {
+ for rows.Next() {
+ var (
+ id, ws, folder, createdBy, updatedBy pgtype.UUID
+ createdAt, updatedAt pgtype.Timestamptz
+ title, createdType, updatedType string
+ matchSource, window string
+ revision int64
+ versionCount int32
+ )
+ if err := rows.Scan(&id, &ws, &folder, &title, &revision, &versionCount,
+ &createdType, &createdBy, &updatedType, &updatedBy, &createdAt, &updatedAt,
+ &matchSource, &window); err != nil {
+ return fmt.Errorf("scan: %w", err)
+ }
+ hit := SearchDocResponse{
+ DocSummaryResponse: DocSummaryResponse{
+ ID: uuidToString(id), WorkspaceID: uuidToString(ws), FolderID: uuidToPtr(folder),
+ Title: title, Revision: revision, VersionCount: versionCount,
+ CreatedByType: createdType, CreatedByID: uuidToString(createdBy),
+ UpdatedByType: updatedType, UpdatedByID: uuidToString(updatedBy),
+ CreatedAt: timestampToString(createdAt), UpdatedAt: timestampToString(updatedAt),
+ },
+ MatchSource: matchSource,
+ }
+ if matchSource == "content" && window != "" {
+ snippet := extractSnippet(window, q)
+ hit.MatchedSnippet = &snippet
+ }
+ resp = append(resp, hit)
+ }
+ return rows.Err()
+ })
+ if err != nil {
+ if writeQueryCancellation(w, r, err) {
+ return
+ }
+ if isSearchStatementTimeout(err) {
+ slog.Warn("search docs timed out", "workspace_id", workspaceID, "query", q, "timeout", searchStatementTimeout)
+ writeError(w, http.StatusServiceUnavailable, "search timed out; please refine your query or try again")
+ return
+ }
+ slog.Warn("search docs failed", "error", err, "workspace_id", workspaceID, "query", q)
+ writeError(w, http.StatusInternalServerError, "failed to search docs")
+ return
+ }
+ if writeQueryCancellation(w, r, ctx.Err()) {
+ return
+ }
+ writeJSON(w, http.StatusOK, map[string]any{"docs": resp})
+}
diff --git a/server/internal/handler/doc_test.go b/server/internal/handler/doc_test.go
index d48cb5af1a..1bb256913d 100644
--- a/server/internal/handler/doc_test.go
+++ b/server/internal/handler/doc_test.go
@@ -3,7 +3,10 @@ package handler
import (
"context"
"net/http"
+ "net/url"
+ "strings"
"testing"
+ "unicode/utf8"
"github.com/multica-ai/multica/server/internal/testutil"
)
@@ -189,3 +192,81 @@ func TestDocTextDropsNULBytes(t *testing.T) {
t.Fatalf("folder rename must drop NUL bytes: %+v", folder)
}
}
+
+func TestSearchDocsRanksTitleHitsAndExcerptsContent(t *testing.T) {
+ create := func(title, content string) DocResponse {
+ t.Helper()
+ var doc DocResponse
+ testutil.Call(t, testHandler.CreateDoc, newRequest("POST", "/api/docs", map[string]any{"title": title, "content": content})).Want(http.StatusCreated).JSON(&doc)
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), "DELETE FROM doc_version WHERE doc_id = $1", doc.ID)
+ testPool.Exec(context.Background(), "DELETE FROM doc WHERE id = $1", doc.ID)
+ })
+ return doc
+ }
+ // Unique words keep this test's rows apart from other docs in the shared DB.
+ long := strings.Repeat("filler text. ", 400) + "Rotate the zephyrine credentials before cutover." + strings.Repeat(" more filler.", 400)
+ inContent := create("Release runbook", long)
+ exact := create("Zephyrine", "")
+ prefix := create("Zephyrine rollout plan", "")
+ cjk := create("值班手册", "遇到 zephyrine 告警先看仪表盘,再联系负责人。")
+ create("Unrelated", "nothing to see")
+
+ type result struct {
+ Docs []SearchDocResponse `json:"docs"`
+ }
+ search := func(q string) result {
+ t.Helper()
+ var out result
+ testutil.Call(t, testHandler.SearchDocs, newRequest("GET", "/api/docs/search?q="+url.QueryEscape(q), nil)).Want(http.StatusOK).JSON(&out)
+ return out
+ }
+ ids := func(r result) []string {
+ out := make([]string, len(r.Docs))
+ for i, d := range r.Docs {
+ out[i] = d.ID
+ }
+ return out
+ }
+
+ got := search("Zephyrine")
+ if want := []string{exact.ID, prefix.ID}; len(got.Docs) < 4 || got.Docs[0].ID != want[0] || got.Docs[1].ID != want[1] {
+ t.Fatalf("exact title, then title prefix, must lead: %v", ids(got))
+ }
+ var content *SearchDocResponse
+ for i := range got.Docs {
+ if got.Docs[i].ID == inContent.ID {
+ content = &got.Docs[i]
+ }
+ }
+ if content == nil || content.MatchSource != "content" || content.MatchedSnippet == nil ||
+ !strings.Contains(*content.MatchedSnippet, "zephyrine credentials") || utf8.RuneCountInString(*content.MatchedSnippet) > 200 {
+ t.Fatalf("a content hit deep in a long doc needs a short excerpt around the match: %+v", content)
+ }
+ if got.Docs[0].MatchSource != "title" || got.Docs[0].MatchedSnippet != nil {
+ t.Fatalf("title hits carry no snippet: %+v", got.Docs[0])
+ }
+
+ // Every term must appear, in either field.
+ if got := search("值班 仪表盘"); len(got.Docs) != 1 || got.Docs[0].ID != cjk.ID {
+ t.Fatalf("multi-term CJK search: %v", ids(got))
+ }
+ // A title with LIKE wildcards still ranks as an exact match.
+ percent := create("100% uptime", "")
+ create("100% uptime review notes", "")
+ if got := search("100% uptime"); len(got.Docs) != 2 || got.Docs[0].ID != percent.ID {
+ t.Fatalf("exact title with %% must rank first: %v", ids(got))
+ }
+ // LIKE wildcards in the query are literal.
+ if got := search("%_"); len(got.Docs) != 0 {
+ t.Fatalf("a literal %% must not match everything: %v", ids(got))
+ }
+ testutil.Call(t, testHandler.SearchDocs, newRequest("GET", "/api/docs/search?q=", nil)).Want(http.StatusBadRequest)
+ cross := newRequest("GET", "/api/docs/search?q=zephyrine", nil)
+ cross.Header.Set("X-Workspace-ID", "00000000-0000-4000-8000-000000000099")
+ var other result
+ testutil.Call(t, testHandler.SearchDocs, cross).JSON(&other)
+ if len(other.Docs) != 0 {
+ t.Fatalf("search leaked across workspaces: %v", ids(other))
+ }
+}