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: wire duplicate scan embedding prefilter

nash_sua343306fce9c
diff --git a/src/lib/__tests__/dedup_embedding.test.ts b/src/lib/__tests__/dedup_embedding.test.ts
index 94b1b746..06ccf860 100644
--- a/src/lib/__tests__/dedup_embedding.test.ts
+++ b/src/lib/__tests__/dedup_embedding.test.ts
@@ -1,15 +1,15 @@
/**
* dedup_embedding.test.ts — unit tests for #359 prefilter (R4)
*/
-import { describe, it, expect, vi } from 'vitest';
+import { describe, it, expect, vi } from "vitest"
import {
candidatePairs,
clusterByPairs,
cosineSimilarity,
pageToEmbeddingText,
type Page,
-} from '../dedup_embedding';
-import type { EmbeddingConfig } from '@/stores/wiki-store';
+} from "../dedup_embedding"
+import type { EmbeddingConfig } from "@/stores/wiki-store"
// Mock fetchEmbedding to produce realistic, sparse vectors.
// Strategy: numeric id suffix → topic axis (mod dim). Pages with same
@@ -17,52 +17,52 @@ import type { EmbeddingConfig } from '@/stores/wiki-store';
// consecutive ids (p0, p1, p2, ...) land on consecutive axes → low mutual
// similarity. This mirrors real-world embeddings where distinct topics
// have distinct dominant axes.
-vi.mock('../embedding', () => ({
+vi.mock("../embedding", () => ({
fetchEmbedding: vi.fn(async (text: string) => {
- const dim = 64;
- const v = new Array(dim).fill(0);
+ const dim = 64
+ const v = new Array(dim).fill(0)
// Extract numeric portion from the input text (pageId is first line)
- const idLine = text.split('\n')[0] ?? '';
- const numMatch = idLine.match(/\d+/);
- const num = numMatch ? parseInt(numMatch[0], 10) : 0;
- const topicAxis = num % dim;
- v[topicAxis] = 1.0;
- v[(topicAxis + 1) % dim] = 0.05;
- v[(topicAxis - 1 + dim) % dim] = 0.03;
- return v;
+ const idLine = text.split("\n")[0] ?? ""
+ const numMatch = idLine.match(/\d+/)
+ const num = numMatch ? parseInt(numMatch[0], 10) : 0
+ const topicAxis = num % dim
+ v[topicAxis] = 1.0
+ v[(topicAxis + 1) % dim] = 0.05
+ v[(topicAxis - 1 + dim) % dim] = 0.03
+ return v
}),
-}));
+}))
const testCfg: EmbeddingConfig = {
enabled: true,
- endpoint: 'http://localhost:0/v1/embeddings',
- apiKey: 'mock-key',
- model: 'mock-embedder',
-};
+ endpoint: "http://localhost:0/v1/embeddings",
+ apiKey: "mock-key",
+ model: "mock-embedder",
+}
-const page = (id: string, title: string, body = ''): Page => ({
+const page = (id: string, title: string, body = ""): Page => ({
id, title, body, tags: [],
-});
+})
describe('pageToEmbeddingText', () => {
it('concatenates title + tags + body', () => {
const text = pageToEmbeddingText({
- id: 'p1', title: 'Foo', body: 'bar baz', tags: ['a', 'b'],
- });
- expect(text).toBe('Foo\na b\nbar baz');
- });
+ id: "p1", title: "Foo", body: "bar baz", tags: ["a", "b"],
+ })
+ expect(text).toBe("p1\nFoo\na b\nbar baz")
+ })
it('truncates body at budget', () => {
- const longBody = 'x'.repeat(2000);
- const text = pageToEmbeddingText({ id: 'p2', title: 'T', body: longBody }, 100);
- expect(text.length).toBeLessThan(120);
- expect(text).toContain('x'.repeat(100));
- });
+ const longBody = "x".repeat(2000)
+ const text = pageToEmbeddingText({ id: "p2", title: "T", body: longBody }, 100)
+ expect(text.length).toBeLessThan(120)
+ expect(text).toContain("x".repeat(100))
+ })
it('handles empty tags and body', () => {
- expect(pageToEmbeddingText({ id: 'p3', title: 'Solo' })).toBe('Solo');
- });
-});
+ expect(pageToEmbeddingText({ id: "p3", title: "Solo" })).toBe("p3\nSolo")
+ })
+})
describe('cosineSimilarity', () => {
it('returns 1 for identical vectors', () => {
@@ -150,13 +150,67 @@ describe('candidatePairs', () => {
page('p4', 'D'),
];
// p3 and p4 both have id-axes → high sim → should pair
- const pairs = await candidatePairs(pages, testCfg, { threshold: 0.5 });
+ const pairs = await candidatePairs(pages, testCfg, {
+ minSuccessRatio: 0.5,
+ threshold: 0.5,
+ });
// null embeddings: p1 and p2 won't contribute as SOURCE; may still appear as TARGET
// but no pairs should reference them since no other page has a vector to compare
expect(pairs.every(([a, b]) => a !== 'p1' && b !== 'p1' && a !== 'p2' && b !== 'p2')).toBe(true);
// restore
(fetchEmbedding as any).mockImplementation(origFetch);
});
+
+ it("throws when too few pages embed successfully", async () => {
+ const { fetchEmbedding } = await import("../embedding");
+ const origFetch = (fetchEmbedding as any).getMockImplementation();
+ (fetchEmbedding as any).mockImplementation(async () => null);
+
+ await expect(
+ candidatePairs(
+ [page("p1", "A"), page("p2", "B"), page("p3", "C")],
+ testCfg,
+ ),
+ ).rejects.toThrow(/could not embed enough pages|embedded only/i);
+
+ (fetchEmbedding as any).mockImplementation(origFetch);
+ });
+
+ it("throws when most pages fail to embed", async () => {
+ const { fetchEmbedding } = await import("../embedding");
+ const origFetch = (fetchEmbedding as any).getMockImplementation();
+ (fetchEmbedding as any)
+ .mockImplementationOnce(async () => [1, 0])
+ .mockImplementationOnce(async () => [1, 0])
+ .mockImplementation(async () => null);
+
+ await expect(
+ candidatePairs(
+ [
+ page("p1", "A"),
+ page("p2", "B"),
+ page("p3", "C"),
+ page("p4", "D"),
+ ],
+ testCfg,
+ ),
+ ).rejects.toThrow(/embedded only 2\/4/i);
+
+ (fetchEmbedding as any).mockImplementation(origFetch);
+ });
+
+ it("honors an already-aborted signal before embedding work starts", async () => {
+ const controller = new AbortController();
+ controller.abort();
+
+ await expect(
+ candidatePairs(
+ [page("p1", "A"), page("p2", "B")],
+ testCfg,
+ { signal: controller.signal },
+ ),
+ ).rejects.toThrow(/cancelled/i);
+ });
});
describe('clusterByPairs', () => {
@@ -186,4 +240,4 @@ describe('clusterByPairs', () => {
const groups = clusterByPairs(ids, pairs);
expect(groups.length).toBe(1);
});
-});
\ No newline at end of file
+});
diff --git a/src/lib/dedup-runner.test.ts b/src/lib/dedup-runner.test.ts
index e8661a6e..29d2b9e1 100644
--- a/src/lib/dedup-runner.test.ts
+++ b/src/lib/dedup-runner.test.ts
@@ -10,13 +10,48 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
// vi.mock is hoisted above imports; vi.hoisted keeps the fn out of the TDZ.
-const { mockStreamChat } = vi.hoisted(() => ({ mockStreamChat: vi.fn() }))
+const {
+ mockCandidatePairs,
+ mockClusterByPairs,
+ mockListDirectory,
+ mockLoadEmbeddingConfig,
+ mockLoadNotDuplicates,
+ mockReadFile,
+ mockStreamChat,
+} = vi.hoisted(() => ({
+ mockCandidatePairs: vi.fn(),
+ mockClusterByPairs: vi.fn(),
+ mockListDirectory: vi.fn(),
+ mockLoadEmbeddingConfig: vi.fn(),
+ mockLoadNotDuplicates: vi.fn(),
+ mockReadFile: vi.fn(),
+ mockStreamChat: vi.fn(),
+}))
vi.mock("./llm-client", async () => {
const actual = await vi.importActual<typeof import("./llm-client")>("./llm-client")
return { ...actual, streamChat: mockStreamChat }
})
+vi.mock("@/commands/fs", () => ({
+ listDirectory: mockListDirectory,
+ readFile: mockReadFile,
+ writeFile: vi.fn(),
+ deleteFile: vi.fn(),
+}))
+vi.mock("@/lib/project-store", () => ({
+ loadEmbeddingConfig: mockLoadEmbeddingConfig,
+}))
+vi.mock("./dedup-storage", () => ({
+ loadNotDuplicates: mockLoadNotDuplicates,
+}))
+vi.mock("@/lib/dedup_embedding", () => ({
+ candidatePairs: mockCandidatePairs,
+ clusterByPairs: mockClusterByPairs,
+ DuplicatePrefilterCancelledError: class DuplicatePrefilterCancelledError extends Error {
+ name = "AbortError"
+ },
+}))
-import { buildDedupLlmCall } from "./dedup-runner"
+import { buildDedupLlmCall, runDuplicateDetection } from "./dedup-runner"
import type { LlmConfig } from "@/stores/wiki-store"
const cfg: LlmConfig = {
@@ -29,10 +64,88 @@ const cfg: LlmConfig = {
maxContextSize: 8192,
}
+const FOO_PATH = "/project/wiki/entities/foo.md"
+const BAR_PATH = "/project/wiki/entities/bar.md"
+const BAZ_PATH = "/project/wiki/entities/baz.md"
+const FOO_REL = "wiki/entities/foo.md"
+const BAR_REL = "wiki/entities/bar.md"
+
beforeEach(() => {
+ mockCandidatePairs.mockReset()
+ mockClusterByPairs.mockReset()
+ mockListDirectory.mockReset()
+ mockLoadEmbeddingConfig.mockReset()
+ mockLoadNotDuplicates.mockReset()
+ mockReadFile.mockReset()
mockStreamChat.mockReset()
})
+function setupThreePageProject() {
+ mockListDirectory.mockResolvedValue([
+ {
+ name: "wiki",
+ path: "/project/wiki",
+ is_dir: true,
+ children: [
+ {
+ name: "entities",
+ path: "/project/wiki/entities",
+ is_dir: true,
+ children: [
+ { name: "foo.md", path: FOO_PATH, is_dir: false },
+ { name: "bar.md", path: BAR_PATH, is_dir: false },
+ { name: "baz.md", path: BAZ_PATH, is_dir: false },
+ ],
+ },
+ ],
+ },
+ ])
+ mockReadFile.mockImplementation(async (path: string) => {
+ const slug = path.split("/").pop()?.replace(/\.md$/, "") ?? "unknown"
+ return `---\ntype: entity\ntitle: ${slug}\ntags: []\n---\n${slug} body`
+ })
+}
+
+function setupEmbeddingConfig(enabled = true) {
+ mockLoadEmbeddingConfig.mockResolvedValue({
+ enabled,
+ endpoint: "http://localhost:1234/v1/embeddings",
+ apiKey: "",
+ model: "mock",
+ })
+}
+
+function setupLargeProject(count = 251) {
+ const children = Array.from({ length: count }, (_, i) => ({
+ name: `p${i}.md`,
+ path: `/project/wiki/entities/p${i}.md`,
+ is_dir: false,
+ }))
+ mockListDirectory.mockResolvedValue([
+ {
+ name: "wiki",
+ path: "/project/wiki",
+ is_dir: true,
+ children: [
+ { name: "entities", path: "/project/wiki/entities", is_dir: true, children },
+ ],
+ },
+ ])
+ mockReadFile.mockImplementation(async (path: string) => {
+ const slug = path.split("/").pop()?.replace(/\.md$/, "") ?? "unknown"
+ return `---\ntype: entity\ntitle: ${slug}\ntags: []\n---\n${slug} body`
+ })
+}
+
+function mockDetectorGroup(slugs: string[] = ["foo", "bar"]) {
+ mockStreamChat.mockImplementation(async (_c, _m, cb) => {
+ cb.onToken(JSON.stringify({
+ groups: [{ slugs, reason: "same topic", confidence: "high" }],
+ }))
+ cb.onDone()
+ })
+}
+
describe("buildDedupLlmCall", () => {
it("disables thinking and caps output so reasoning models answer instead of streaming chain-of-thought to the backstop", async () => {
mockStreamChat.mockImplementation(async (_c, _m, cb) => {
@@ -89,3 +202,127 @@ describe("buildDedupLlmCall", () => {
)
})
})
+
+describe("runDuplicateDetection embedding prefilter", () => {
+ it("sends only embedding candidate summaries to the LLM detector", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockResolvedValue([[FOO_REL, BAR_REL]])
+ mockClusterByPairs.mockReturnValue([[FOO_REL, BAR_REL]])
+ mockDetectorGroup()
+
+ const result = await runDuplicateDetection("/project", cfg)
+
+ expect(result).toEqual([
+ { slugs: ["foo", "bar"], reason: "same topic", confidence: "high" },
+ ])
+ expect(mockCandidatePairs).toHaveBeenCalledOnce()
+ const detectorUserMessage = mockStreamChat.mock.calls[0][1][1].content
+ expect(detectorUserMessage).toContain("slug=foo")
+ expect(detectorUserMessage).toContain("slug=bar")
+ expect(detectorUserMessage).not.toContain("slug=baz")
+ })
+
+ it("falls back to the full LLM scan when the embedding prefilter fails", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockRejectedValue(new Error("embedding endpoint unavailable"))
+ mockDetectorGroup()
+
+ await runDuplicateDetection("/project", cfg)
+
+ const detectorUserMessage = mockStreamChat.mock.calls[0][1][1].content
+ expect(detectorUserMessage).toContain("slug=foo")
+ expect(detectorUserMessage).toContain("slug=bar")
+ expect(detectorUserMessage).toContain("slug=baz")
+ })
+
+ it("falls back to the full LLM scan when persisted embedding config is malformed", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ mockLoadEmbeddingConfig.mockResolvedValue({
+ enabled: true,
+ apiKey: "",
+ model: "mock",
+ })
+ mockDetectorGroup()
+
+ await runDuplicateDetection("/project", cfg)
+
+ expect(mockCandidatePairs).not.toHaveBeenCalled()
+ const detectorUserMessage = mockStreamChat.mock.calls[0][1][1].content
+ expect(detectorUserMessage).toContain("slug=baz")
+ })
+
+ it("falls back to the full LLM scan for small wikis when the prefilter returns no candidates", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockResolvedValue([])
+ mockDetectorGroup()
+
+ const result = await runDuplicateDetection("/project", cfg)
+
+ expect(result).toEqual([
+ { slugs: ["foo", "bar"], reason: "same topic", confidence: "high" },
+ ])
+ const detectorUserMessage = mockStreamChat.mock.calls[0][1][1].content
+ expect(detectorUserMessage).toContain("slug=foo")
+ expect(detectorUserMessage).toContain("slug=bar")
+ expect(detectorUserMessage).toContain("slug=baz")
+ expect(mockClusterByPairs).not.toHaveBeenCalled()
+ })
+
+ it("short-circuits large wiki scans when the prefilter returns no candidates", async () => {
+ setupLargeProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockResolvedValue([])
+
+ const result = await runDuplicateDetection("/project", cfg)
+
+ expect(result).toEqual([])
+ expect(mockStreamChat).not.toHaveBeenCalled()
+ expect(mockClusterByPairs).not.toHaveBeenCalled()
+ })
+
+ it("does not fall back to the full LLM scan for large wikis when embedding coverage is too low", async () => {
+ setupLargeProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockRejectedValue(new Error("Duplicate prefilter embedded only 2/251 pages"))
+
+ const result = await runDuplicateDetection("/project", cfg)
+
+ expect(result).toEqual([])
+ expect(mockStreamChat).not.toHaveBeenCalled()
+ })
+
+ it("keeps the not-duplicates whitelist active on the prefiltered path", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([["foo", "bar"]])
+ setupEmbeddingConfig()
+ mockCandidatePairs.mockResolvedValue([[FOO_REL, BAR_REL]])
+ mockClusterByPairs.mockReturnValue([[FOO_REL, BAR_REL]])
+
+ const result = await runDuplicateDetection("/project", cfg)
+
+ expect(result).toEqual([])
+ expect(mockStreamChat).not.toHaveBeenCalled()
+ })
+
+ it("propagates cancellation instead of falling back to a full scan", async () => {
+ setupThreePageProject()
+ mockLoadNotDuplicates.mockResolvedValue([])
+ setupEmbeddingConfig()
+ const controller = new AbortController()
+ controller.abort()
+ mockCandidatePairs.mockRejectedValue(new Error("Duplicate scan cancelled"))
+
+ await expect(runDuplicateDetection("/project", cfg, { signal: controller.signal }))
+ .rejects.toThrow(/cancelled/i)
+ expect(mockStreamChat).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/dedup-runner.ts b/src/lib/dedup-runner.ts
index 2d45635d..06cc8228 100644
--- a/src/lib/dedup-runner.ts
+++ b/src/lib/dedup-runner.ts
@@ -6,8 +6,16 @@
*/
import { listDirectory, readFile, writeFile, deleteFile } from "@/commands/fs"
import { streamChat } from "@/lib/llm-client"
+import {
+ candidatePairs,
+ clusterByPairs,
+ DuplicatePrefilterCancelledError,
+ type CandidatePair,
+ type Page as DedupEmbeddingPage,
+} from "@/lib/dedup_embedding"
+import { loadEmbeddingConfig } from "@/lib/project-store"
import { normalizePath } from "@/lib/path-utils"
-import type { LlmConfig } from "@/stores/wiki-store"
+import type { EmbeddingConfig, LlmConfig } from "@/stores/wiki-store"
import type { FileNode } from "@/types/wiki"
/**
@@ -21,6 +29,15 @@ import type { FileNode } from "@/types/wiki"
* 30-min hang into a fast (truncated) response instead.
*/
const DEDUP_DETECTION_MAX_TOKENS = 8_192
+// Conservative defaults: keep enough neighbors for recall while cutting the
+// LLM detector prompt into small candidate batches. The threshold is deliberately
+// below "near duplicate" territory because this tool must catch cross-language
+// aliases, where cosine scores can be weaker on non-multilingual embedders.
+const DEDUP_PREFILTER_TOP_K = 8
+const DEDUP_PREFILTER_THRESHOLD = 0.68
+const DEDUP_PREFILTER_MAX_PAGES = 5_000
+const DEDUP_DETECTOR_BATCH_SUMMARIES = 80
+const DEDUP_EMPTY_PREFILTER_FULL_SCAN_LIMIT = 250
/**
* Merge rewrites a COMPLETE page that gets written to disk, so it needs
@@ -178,12 +195,163 @@ export async function runDuplicateDetection(
if (summaries.length < 2) return []
const notDup = await loadNotDuplicates(projectPath)
const llm = buildDedupLlmCall(llmConfig, DEDUP_DETECTION_MAX_TOKENS)
+ const embeddingConfig = await loadEmbeddingConfig()
+
+ const embeddingEndpoint =
+ typeof embeddingConfig?.endpoint === "string" ? embeddingConfig.endpoint.trim() : ""
+ if (embeddingConfig?.enabled && embeddingEndpoint) {
+ try {
+ return await detectDuplicateGroupsWithEmbeddingPrefilter(
+ summaries,
+ embeddingConfig,
+ llm,
+ {
+ signal: options.signal,
+ notDuplicates: notDup,
+ },
+ )
+ } catch (err) {
+ if (isAbortError(err) || options.signal?.aborted) throw err
+ if (summaries.length > DEDUP_EMPTY_PREFILTER_FULL_SCAN_LIMIT && isEmbeddingCoverageError(err)) {
+ console.warn("[dedup] embedding prefilter coverage too low; skipping full fallback for large wiki:", err)
+ return []
+ }
+ console.warn("[dedup] embedding prefilter failed; falling back to full LLM scan:", err)
+ }
+ }
+
return detectDuplicateGroups(summaries, llm, {
signal: options.signal,
notDuplicates: notDup,
})
}
+async function detectDuplicateGroupsWithEmbeddingPrefilter(
+ summaries: EntitySummary[],
+ embeddingConfig: EmbeddingConfig,
+ llm: DedupLlmCall,
+ options: { signal?: AbortSignal; notDuplicates?: string[][] },
+): Promise<DuplicateGroup[]> {
+ const pages = summaries.map(summaryToEmbeddingPage)
+ const pairs = await candidatePairs(pages, embeddingConfig, {
+ topK: DEDUP_PREFILTER_TOP_K,
+ threshold: DEDUP_PREFILTER_THRESHOLD,
+ maxPages: DEDUP_PREFILTER_MAX_PAGES,
+ signal: options.signal,
+ })
+ if (pairs.length === 0) {
+ // Preserve recall for small/medium wikis: a weak or non-multilingual
+ // embedder can miss exactly the cross-language aliases the LLM detector
+ // is meant to find. For large wikis, the old full scan is what caused
+ // #359 hangs, so no candidates means no detector call.
+ return summaries.length <= DEDUP_EMPTY_PREFILTER_FULL_SCAN_LIMIT
+ ? detectDuplicateGroups(summaries, llm, options)
+ : []
+ }
+
+ const summaryByPath = new Map(summaries.map((s) => [s.path, s]))
+ const filteredPairs = filterWhitelistedPairs(pairs, summaryByPath, options.notDuplicates ?? [])
+ if (filteredPairs.length === 0) return []
+
+ const pageIds = summaries.map((s) => s.path)
+ const clusters = clusterByPairs(pageIds, filteredPairs)
+ if (clusters.length === 0) return []
+
+ const batches = batchCandidateClusters(clusters, summaryByPath)
+ const out: DuplicateGroup[] = []
+
+ for (const batch of batches) {
+ if (options.signal?.aborted) throw new Error("Duplicate scan cancelled")
+ const detected = await detectDuplicateGroups(batch, llm, options)
+ out.push(...detected)
+ }
+
+ return uniqueDuplicateGroups(out)
+}
+
+function summaryToEmbeddingPage(summary: EntitySummary): DedupEmbeddingPage {
+ return {
+ id: summary.path,
+ title: summary.title,
+ body: summary.description ?? "",
+ tags: summary.tags,
+ }
+}
+
+function batchCandidateClusters(
+ clusters: string[][],
+ summaryByPath: Map<string, EntitySummary>,
+): EntitySummary[][] {
+ const batches: EntitySummary[][] = []
+ let current: EntitySummary[] = []
+
+ for (const cluster of clusters) {
+ const summaries = cluster
+ .map((pageId) => summaryByPath.get(pageId))
+ .filter((summary): summary is EntitySummary => !!summary)
+ if (summaries.length < 2) continue
+
+ if (
+ current.length > 0
+ && current.length + summaries.length > DEDUP_DETECTOR_BATCH_SUMMARIES
+ ) {
+ batches.push(current)
+ current = []
+ }
+
+ current.push(...summaries)
+
+ if (current.length >= DEDUP_DETECTOR_BATCH_SUMMARIES) {
+ batches.push(current)
+ current = []
+ }
+ }
+
+ if (current.length > 0) batches.push(current)
+ return batches
+}
+
+function uniqueDuplicateGroups(groups: DuplicateGroup[]): DuplicateGroup[] {
+ const seen = new Set<string>()
+ const out: DuplicateGroup[] = []
+ for (const group of groups) {
+ const key = group.slugs.map((slug) => slug.toLowerCase()).sort().join("\t")
+ if (seen.has(key)) continue
+ seen.add(key)
+ out.push(group)
+ }
+ return out
+}
+
+function filterWhitelistedPairs(
+ pairs: CandidatePair[],
+ summaryByPath: Map<string, EntitySummary>,
+ notDuplicates: string[][],
+): CandidatePair[] {
+ if (notDuplicates.length === 0) return pairs
+ const notDupSet = new Set(notDuplicates.map(normalizeSlugGroupKey))
+ return pairs.filter(([a, b]) => {
+ const left = summaryByPath.get(a)?.slug
+ const right = summaryByPath.get(b)?.slug
+ if (!left || !right) return true
+ return !notDupSet.has(normalizeSlugGroupKey([left, right]))
+ })
+}
+
+function normalizeSlugGroupKey(slugs: readonly string[]): string {
+ return slugs.map((slug) => slug.toLowerCase()).sort().join("\t")
+}
+
+function isAbortError(err: unknown): boolean {
+ return err instanceof DuplicatePrefilterCancelledError
+ || (err instanceof Error && err.name === "AbortError")
+}
+
+function isEmbeddingCoverageError(err: unknown): boolean {
+ return err instanceof Error
+ && /could not embed enough pages|embedded only \d+\/\d+ pages/i.test(err.message)
+}
+
/**
* Stage 3 + persistence: execute one user-confirmed merge.
*
diff --git a/src/lib/dedup_embedding.ts b/src/lib/dedup_embedding.ts
index 33c759e9..2c631e0e 100644
--- a/src/lib/dedup_embedding.ts
+++ b/src/lib/dedup_embedding.ts
@@ -7,44 +7,60 @@
*
* Uses real fetchEmbedding() from ./embedding (raw text → vector API).
*/
-import { fetchEmbedding } from './embedding';
-import type { EmbeddingConfig } from '@/stores/wiki-store';
+import { fetchEmbedding } from "./embedding"
+import type { EmbeddingConfig } from "@/stores/wiki-store"
export interface Page {
- id: string;
- title: string;
- body?: string;
- tags?: string[];
+ id: string
+ title: string
+ body?: string
+ tags?: string[]
}
export interface CandidateOptions {
- topK?: number; // default 8
- threshold?: number; // default 0.82 (cosine, 0..1)
- maxPages?: number; // hard cap to avoid OOM, default 5000
+ topK?: number
+ threshold?: number
+ maxPages?: number
+ signal?: AbortSignal
+ /**
+ * If too many embeddings fail, callers should fall back to the old full scan
+ * instead of silently missing most pages. Default: 0.8.
+ */
+ minSuccessRatio?: number
/**
* Per-page character budget for the embedding input text.
* Real pages can be megabytes; we cap to stay within embedding context windows.
* Default 1500 chars (matches chunker default).
*/
- textBudgetChars?: number;
+ textBudgetChars?: number
}
-export type CandidatePair = readonly [string, string];
+export type CandidatePair = readonly [string, string]
+
+export class DuplicatePrefilterCancelledError extends Error {
+ name = "AbortError"
+}
+
+function throwIfAborted(signal?: AbortSignal) {
+ if (signal?.aborted) throw new DuplicatePrefilterCancelledError("Duplicate scan cancelled")
+}
/**
* Cosine similarity between two equal-length vectors. Returns 0 if either is
* zero, vectors differ in length, or either is null/undefined (embedding failed).
*/
export function cosineSimilarity(a: number[] | null | undefined, b: number[] | null | undefined): number {
- if (!a || !b || a.length !== b.length) return 0;
- let dot = 0, na = 0, nb = 0;
+ if (!a || !b || a.length !== b.length) return 0
+ let dot = 0
+ let na = 0
+ let nb = 0
for (let i = 0; i < a.length; i++) {
- dot += a[i] * b[i];
- na += a[i] * a[i];
- nb += b[i] * b[i];
+ dot += a[i] * b[i]
+ na += a[i] * a[i]
+ nb += b[i] * b[i]
}
- const denom = Math.sqrt(na) * Math.sqrt(nb);
- return denom === 0 ? 0 : dot / denom;
+ const denom = Math.sqrt(na) * Math.sqrt(nb)
+ return denom === 0 ? 0 : dot / denom
}
/**
@@ -52,9 +68,15 @@ export function cosineSimilarity(a: number[] | null | undefined, b: number[] | n
* Mirrors embedPage's chunker input but keeps it short for similarity comparison.
*/
export function pageToEmbeddingText(page: Page, budget = 1500): string {
- const tagPart = (page.tags ?? []).join(' ');
- const parts = [page.title, tagPart, (page.body ?? '').slice(0, budget)];
- return parts.filter(Boolean).join('\n');
+ const tagPart = (page.tags ?? []).join(" ")
+ const idPart = page.id.split("/").pop()?.replace(/\.md$/i, "") ?? page.id
+ const parts = [
+ idPart,
+ page.title,
+ tagPart,
+ (page.body ?? "").slice(0, budget),
+ ]
+ return parts.filter(Boolean).join("\n")
}
/**
@@ -64,16 +86,18 @@ export function pageToEmbeddingText(page: Page, budget = 1500): string {
export async function embedPages(
pages: Page[],
cfg: EmbeddingConfig,
- opts: { textBudgetChars?: number } = {},
+ opts: { signal?: AbortSignal; textBudgetChars?: number } = {},
): Promise<Map<string, number[] | null>> {
- const out = new Map<string, number[] | null>();
- const budget = opts.textBudgetChars ?? 1500;
+ const out = new Map<string, number[] | null>()
+ const budget = opts.textBudgetChars ?? 1500
for (const p of pages) {
- const text = pageToEmbeddingText(p, budget);
- const vec = await fetchEmbedding(text, cfg);
- out.set(p.id, vec);
+ throwIfAborted(opts.signal)
+ const text = pageToEmbeddingText(p, budget)
+ const vec = await fetchEmbedding(text, cfg)
+ throwIfAborted(opts.signal)
+ out.set(p.id, vec)
}
- return out;
+ return out
}
/**
@@ -88,44 +112,61 @@ export async function candidatePairs(
cfg: EmbeddingConfig,
opts: CandidateOptions = {},
): Promise<CandidatePair[]> {
- const topK = opts.topK ?? 8;
- const threshold = opts.threshold ?? 0.82;
- const maxPages = opts.maxPages ?? 5000;
-
- if (pages.length === 0) return [];
- const subset = pages.slice(0, maxPages);
+ const topK = opts.topK ?? 8
+ const threshold = opts.threshold ?? 0.82
+ const maxPages = opts.maxPages ?? 5000
+ const minSuccessRatio = opts.minSuccessRatio ?? 0.8
+
+ if (pages.length === 0) return []
+ const subset = pages.slice(0, maxPages)
+ if (pages.length > subset.length) {
+ console.warn(
+ `[dedup] embedding prefilter limited scan to ${subset.length}/${pages.length} pages`,
+ )
+ }
const embeddings = await embedPages(subset, cfg, {
+ signal: opts.signal,
textBudgetChars: opts.textBudgetChars,
- });
+ })
+
+ const embeddedCount = [...embeddings.values()].filter((v) => v && v.length > 0).length
+ if (subset.length >= 2 && embeddedCount < 2) {
+ throw new Error("Duplicate prefilter could not embed enough pages")
+ }
+ if (subset.length > 0 && embeddedCount / subset.length < minSuccessRatio) {
+ throw new Error(
+ `Duplicate prefilter embedded only ${embeddedCount}/${subset.length} pages`,
+ )
+ }
- const pairSet = new Set<string>();
- const pairs: CandidatePair[] = [];
+ const pairSet = new Set<string>()
+ const pairs: CandidatePair[] = []
for (let i = 0; i < subset.length; i++) {
- const vi = embeddings.get(subset[i].id);
- if (!vi) continue;
- const scored: Array<{ j: number; sim: number }> = [];
+ const vi = embeddings.get(subset[i].id)
+ if (!vi) continue
+ const scored: Array<{ j: number; sim: number }> = []
for (let j = 0; j < subset.length; j++) {
- if (i === j) continue;
- const vj = embeddings.get(subset[j].id);
- const sim = cosineSimilarity(vi, vj);
- if (sim >= threshold) scored.push({ j, sim });
+ if (i === j) continue
+ const vj = embeddings.get(subset[j].id)
+ const sim = cosineSimilarity(vi, vj)
+ if (sim >= threshold) scored.push({ j, sim })
}
- scored.sort((a, b) => b.sim - a.sim);
+ scored.sort((a, b) => b.sim - a.sim)
for (let k = 0; k < Math.min(topK, scored.length); k++) {
- const a = subset[i].id;
- const b = subset[scored[k].j].id;
- const key = a < b ? `${a}\t${b}` : `${b}\t${a}`;
+ const a = subset[i].id
+ const b = subset[scored[k].j].id
+ const key = a < b ? `${a}\t${b}` : `${b}\t${a}`
if (!pairSet.has(key)) {
- pairSet.add(key);
- pairs.push([a, b] as const);
+ pairSet.add(key)
+ pairs.push([a, b] as const)
}
}
}
- return pairs;
+ return pairs
}
/**
@@ -136,33 +177,34 @@ export function clusterByPairs(
pageIds: string[],
pairs: CandidatePair[],
): string[][] {
- const parent = new Map<string, string>();
- for (const id of pageIds) parent.set(id, id);
+ const parent = new Map<string, string>()
+ for (const id of pageIds) parent.set(id, id)
const find = (x: string): string => {
- let root = x;
- while (parent.get(root) !== root) root = parent.get(root)!;
+ let root = x
+ while (parent.get(root) !== root) root = parent.get(root)!
// path compression
- let cur = x;
+ let cur = x
while (parent.get(cur) !== root) {
- const next = parent.get(cur)!;
- parent.set(cur, root);
- cur = next;
+ const next = parent.get(cur)!
+ parent.set(cur, root)
+ cur = next
}
- return root;
- };
+ return root
+ }
for (const [a, b] of pairs) {
- const ra = find(a), rb = find(b);
- if (ra !== rb) parent.set(ra, rb);
+ const ra = find(a)
+ const rb = find(b)
+ if (ra !== rb) parent.set(ra, rb)
}
- const groups = new Map<string, string[]>();
+ const groups = new Map<string, string[]>()
for (const id of pageIds) {
- const root = find(id);
- if (!groups.has(root)) groups.set(root, []);
- groups.get(root)!.push(id);
+ const root = find(id)
+ if (!groups.has(root)) groups.set(root, [])
+ groups.get(root)!.push(id)
}
- return [...groups.values()].filter(g => g.length > 1);
-}
\ No newline at end of file
+ return [...groups.values()].filter((g) => g.length > 1)
+}