/** * Tests for the source curation pipeline. * * curateSources orchestrates fetching from Wikipedia, Wikidata, and OpenStax, * deduplicates, and stores in DB. getGroundedTeaching builds on curateSources * to generate LLM content with inline citations. We mock all external * dependencies (Prisma, source providers, Claude SDK). */ import { describe, it, expect, vi, beforeEach } from "vitest"; // ── Mock external dependencies ────────────────────────────────────────────── const mockWikipedia = vi.fn(); const mockWikidata = vi.fn(); const mockWikidataExcerpt = vi.fn(); const mockOpenStax = vi.fn(); vi.mock("@/lib/sources/wikipedia", () => ({ fetchWikipediaSources: (...args: unknown[]) => mockWikipedia(...args), verifyWikipediaUrl: vi.fn().mockResolvedValue(true), })); vi.mock("@/lib/sources/wikidata", () => ({ fetchWikidataSource: (...args: unknown[]) => mockWikidata(...args), formatEntityAsExcerpt: (...args: unknown[]) => mockWikidataExcerpt(...args), })); vi.mock("@/lib/sources/openstax", () => ({ fetchOpenStaxSources: (...args: unknown[]) => mockOpenStax(...args), })); // Mock Prisma const mockTopicSourceFindMany = vi.fn(); const mockTopicSourceFindFirst = vi.fn(); const mockTopicSourceCreate = vi.fn(); const mockTopicSourceCount = vi.fn(); const mockTeachingCacheFindUnique = vi.fn(); const mockTeachingCacheCreate = vi.fn(); const mockTeachingCacheDelete = vi.fn(); const mockTopicSourceUpdate = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { topicSource: { findMany: (...args: unknown[]) => mockTopicSourceFindMany(...args), findFirst: (...args: unknown[]) => mockTopicSourceFindFirst(...args), create: (...args: unknown[]) => mockTopicSourceCreate(...args), count: (...args: unknown[]) => mockTopicSourceCount(...args), update: (...args: unknown[]) => mockTopicSourceUpdate(...args), }, teachingCache: { findUnique: (...args: unknown[]) => mockTeachingCacheFindUnique(...args), create: (...args: unknown[]) => mockTeachingCacheCreate(...args), delete: (...args: unknown[]) => mockTeachingCacheDelete(...args), }, }, })); // Mock Claude SDK const mockClaudeCreate = vi.fn(); vi.mock("@/lib/claude", () => ({ claude: { messages: { create: (...args: unknown[]) => mockClaudeCreate(...args), }, }, parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), })); // Import after mocking import { curateSources, getGroundedTeaching, hasSourceCoverage, verifySources, MIN_SOURCES, } from "../curate"; // ── Test data ──────────────────────────────────────────────────────────────── const WIKI_EXTRACT_1 = { title: "Quantum Entanglement", extract: "Quantum entanglement is a phenomenon...", url: "https://en.wikipedia.org/wiki/Quantum_entanglement", }; const WIKI_EXTRACT_2 = { title: "EPR Paradox", extract: "The EPR paradox is a thought experiment...", url: "https://en.wikipedia.org/wiki/EPR_paradox", }; const WIKIDATA_ENTITY = { id: "Q3196", label: "Quantum entanglement", description: "physical phenomenon", url: "https://www.wikidata.org/wiki/Q3196", aliases: ["entanglement"], facts: { instanceOf: ["physical phenomenon"] }, wikipediaUrl: "https://en.wikipedia.org/wiki/Quantum_entanglement", }; const OPENSTAX_SECTION = { bookTitle: "University Physics Volume 3", sectionTitle: "Quantum Entanglement", url: "https://openstax.org/books/university-physics-volume-3/pages/11-4-quantum-entanglement", excerpt: "When two particles become entangled...", }; // ── Tests ──────────────────────────────────────────────────────────────────── beforeEach(() => { vi.clearAllMocks(); mockTopicSourceCreate.mockResolvedValue({}); mockTeachingCacheDelete.mockResolvedValue({}); }); describe("MIN_SOURCES", () => { it("is set to 2", () => { expect(MIN_SOURCES).toBe(2); }); }); describe("curateSources", () => { it("returns cached sources when DB has enough", async () => { const cached = [ { url: "https://a.com", title: "A", excerpt: "...", domain: "wikipedia", license: "CC BY-SA 4.0", confidence: "high" }, { url: "https://b.com", title: "B", excerpt: "...", domain: "wikipedia", license: "CC BY-SA 4.0", confidence: "high" }, ]; mockTopicSourceFindMany.mockResolvedValue(cached); const result = await curateSources("qe-1", "Quantum Entanglement"); expect(result).toHaveLength(2); expect(result[0].url).toBe("https://a.com"); // Should NOT call any source providers expect(mockWikipedia).not.toHaveBeenCalled(); expect(mockWikidata).not.toHaveBeenCalled(); expect(mockOpenStax).not.toHaveBeenCalled(); }); it("fetches from all providers when DB has insufficient sources", async () => { mockTopicSourceFindMany.mockResolvedValue([]); // no cached mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(WIKIDATA_ENTITY); mockWikidataExcerpt.mockReturnValue("Quantum entanglement — physical phenomenon. Aliases: entanglement."); mockOpenStax.mockResolvedValue([OPENSTAX_SECTION]); mockTopicSourceFindFirst.mockResolvedValue(null); // no duplicates const result = await curateSources("qe-1", "Quantum Entanglement", "physics"); expect(result.length).toBeGreaterThanOrEqual(3); // wiki*2 + wikidata + openstax expect(mockWikipedia).toHaveBeenCalledWith("Quantum Entanglement", 3); expect(mockWikidata).toHaveBeenCalledWith("Quantum Entanglement"); expect(mockOpenStax).toHaveBeenCalledWith("Quantum Entanglement", "physics", 1); }); it("stores new sources in DB (skipping duplicates)", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1]); mockWikidata.mockResolvedValue(null); // no wikidata mockOpenStax.mockResolvedValue([]); // no openstax // First source is new, no duplicates found mockTopicSourceFindFirst.mockResolvedValue(null); await curateSources("qe-1", "Quantum Entanglement"); expect(mockTopicSourceCreate).toHaveBeenCalledOnce(); expect(mockTopicSourceCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ topicId: "qe-1", url: WIKI_EXTRACT_1.url, title: WIKI_EXTRACT_1.title, domain: "wikipedia", license: "CC BY-SA 4.0", }), }); }); it("skips storing a source that already exists in DB", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); // Source already exists mockTopicSourceFindFirst.mockResolvedValue({ id: 1, url: WIKI_EXTRACT_1.url }); await curateSources("qe-1", "Quantum Entanglement"); // Should NOT create — it's a duplicate expect(mockTopicSourceCreate).not.toHaveBeenCalled(); }); it("gracefully handles Wikidata failure", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockRejectedValue(new Error("Wikidata timeout")); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await curateSources("qe-1", "Quantum Entanglement"); // Should still return Wikipedia sources expect(result).toHaveLength(2); expect(result.every((s) => s.domain === "wikipedia")).toBe(true); }); it("gracefully handles OpenStax failure", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockRejectedValue(new Error("OpenStax down")); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await curateSources("qe-1", "Quantum Entanglement"); expect(result).toHaveLength(1); expect(result[0].domain).toBe("wikipedia"); }); it("skips Wikidata entities with short excerpts", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1]); mockWikidata.mockResolvedValue(WIKIDATA_ENTITY); mockWikidataExcerpt.mockReturnValue("short"); // <30 chars mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await curateSources("qe-1", "Quantum Entanglement"); // Only Wikipedia, no Wikidata (excerpt too short) expect(result).toHaveLength(1); expect(result.every((s) => s.domain === "wikipedia")).toBe(true); }); it("includes Wikidata with CC0 license", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([]); mockWikidata.mockResolvedValue(WIKIDATA_ENTITY); mockWikidataExcerpt.mockReturnValue("Quantum entanglement — a physical phenomenon in quantum mechanics where particles are correlated."); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await curateSources("qe-1", "Quantum Entanglement"); const wikidataSource = result.find((s) => s.domain === "wikidata"); expect(wikidataSource).toBeDefined(); expect(wikidataSource!.license).toBe("CC0"); }); it("includes OpenStax with CC BY 4.0 license", async () => { mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([OPENSTAX_SECTION]); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await curateSources("qe-1", "Quantum Entanglement", "physics"); const openstaxSource = result.find((s) => s.domain === "openstax"); expect(openstaxSource).toBeDefined(); expect(openstaxSource!.license).toBe("CC BY 4.0"); expect(openstaxSource!.title).toContain("OpenStax"); }); }); describe("getGroundedTeaching", () => { it("returns cached teaching when available", async () => { const cached = { topicId: "qe-1", content: "Quantum entanglement is...\n\nKey points:\n- Point 1\n- Point 2", sourcesJson: JSON.stringify([ { url: "https://en.wikipedia.org/wiki/QE", title: "QE", domain: "wikipedia", license: "CC BY-SA 4.0" }, ]), confidenceScore: "high", verifiedAt: new Date(), }; mockTeachingCacheFindUnique.mockResolvedValue(cached); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); expect(result).not.toBeNull(); expect(result!.cached).toBe(true); expect(result!.topic).toBe("Quantum Entanglement"); expect(result!.confidenceScore).toBe("high"); // Should NOT call curateSources or Claude expect(mockWikipedia).not.toHaveBeenCalled(); expect(mockClaudeCreate).not.toHaveBeenCalled(); }); it("returns null when insufficient sources are available", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); // curateSources returns only 1 source (below MIN_SOURCES=2) mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1]); // only 1 mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); expect(result).toBeNull(); expect(mockClaudeCreate).not.toHaveBeenCalled(); }); it("generates grounded content via Claude when sources are sufficient", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: JSON.stringify({ explanation: "Quantum entanglement [1] connects particles [2].", keyTakeaways: ["Particles are correlated", "Measurement affects both"], }), }], }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement", "intermediate"); expect(result).not.toBeNull(); expect(result!.cached).toBe(false); expect(result!.explanation).toContain("[1]"); expect(result!.keyTakeaways).toHaveLength(2); expect(result!.sources).toHaveLength(2); // Should cache the result expect(mockTeachingCacheCreate).toHaveBeenCalledWith({ data: expect.objectContaining({ topicId: "qe-1", }), }); }); it("sets confidence to 'high' with 3+ sources", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(WIKIDATA_ENTITY); mockWikidataExcerpt.mockReturnValue("Quantum entanglement — physical phenomenon in quantum mechanics."); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: JSON.stringify({ explanation: "...", keyTakeaways: ["a"] }), }], }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); expect(result!.confidenceScore).toBe("high"); }); it("sets confidence to 'moderate' with exactly 2 sources", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: JSON.stringify({ explanation: "...", keyTakeaways: ["a"] }), }], }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); expect(result!.confidenceScore).toBe("moderate"); }); it("stores full CuratedSource shape (including excerpt and confidence) in cache", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: JSON.stringify({ explanation: "X", keyTakeaways: ["Y"] }) }], }); await getGroundedTeaching("qe-1", "Quantum Entanglement"); const createCall = mockTeachingCacheCreate.mock.calls[0][0]; const storedSources = JSON.parse(createCall.data.sourcesJson); expect(storedSources[0]).toHaveProperty("excerpt"); expect(storedSources[0]).toHaveProperty("confidence"); }); it("recovers from corrupted cache JSON by deleting and regenerating", async () => { // Simulate corrupted sourcesJson in cache mockTeachingCacheFindUnique .mockResolvedValueOnce({ topicId: "qe-1", content: "Some explanation", sourcesJson: "NOT VALID JSON {{{", confidenceScore: "high", verifiedAt: new Date(), }) // Second call (after delete + recurse) returns null → triggers fresh generation .mockResolvedValueOnce(null); // After cache delete, fresh generation needs sources mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: JSON.stringify({ explanation: "Fresh", keyTakeaways: ["Z"] }) }], }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); // Should have deleted the corrupted cache expect(mockTeachingCacheDelete).toHaveBeenCalledWith({ where: { topicId: "qe-1" } }); // Should return freshly generated content expect(result).not.toBeNull(); expect(result!.explanation).toBe("Fresh"); expect(result!.cached).toBe(false); }); it("backfills missing confidence field from older cache entries", async () => { // Older cached sourcesJson without confidence field const oldStyleSources = [ { url: "https://a.com", title: "A", excerpt: "...", domain: "wikipedia", license: "CC BY-SA 4.0" }, ]; mockTeachingCacheFindUnique.mockResolvedValue({ topicId: "qe-1", content: "Some explanation\n- Key point", sourcesJson: JSON.stringify(oldStyleSources), confidenceScore: "high", verifiedAt: new Date(), }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); expect(result).not.toBeNull(); // confidence should be backfilled to "high" default expect(result!.sources[0].confidence).toBe("high"); }); it("handles non-JSON Claude response by using raw text as explanation", async () => { mockTeachingCacheFindUnique.mockResolvedValue(null); mockTopicSourceFindMany.mockResolvedValue([]); mockWikipedia.mockResolvedValue([WIKI_EXTRACT_1, WIKI_EXTRACT_2]); mockWikidata.mockResolvedValue(null); mockOpenStax.mockResolvedValue([]); mockTopicSourceFindFirst.mockResolvedValue(null); mockTeachingCacheCreate.mockResolvedValue({}); // Claude returns plain text instead of JSON mockClaudeCreate.mockResolvedValue({ content: [{ type: "text", text: "Here is a plain explanation without JSON formatting." }], }); const result = await getGroundedTeaching("qe-1", "Quantum Entanglement"); // Should not throw; falls back gracefully expect(result).not.toBeNull(); expect(result!.explanation).toBe("Here is a plain explanation without JSON formatting."); expect(result!.keyTakeaways).toHaveLength(0); expect(result!.cached).toBe(false); }); }); describe("hasSourceCoverage", () => { it("returns true when count >= MIN_SOURCES", async () => { mockTopicSourceCount.mockResolvedValue(3); const result = await hasSourceCoverage("qe-1"); expect(result).toBe(true); expect(mockTopicSourceCount).toHaveBeenCalledWith({ where: { topicId: "qe-1" }, }); }); it("returns false when count < MIN_SOURCES", async () => { mockTopicSourceCount.mockResolvedValue(1); const result = await hasSourceCoverage("qe-1"); expect(result).toBe(false); }); it("returns true at exactly MIN_SOURCES", async () => { mockTopicSourceCount.mockResolvedValue(MIN_SOURCES); expect(await hasSourceCoverage("qe-1")).toBe(true); }); it("returns false at zero", async () => { mockTopicSourceCount.mockResolvedValue(0); expect(await hasSourceCoverage("qe-1")).toBe(false); }); }); describe("verifySources", () => { it("returns count of verified sources", async () => { mockTopicSourceFindMany.mockResolvedValue([ { id: 1, url: "https://a.com", topicId: "qe-1" }, { id: 2, url: "https://b.com", topicId: "qe-1" }, ]); mockTopicSourceUpdate.mockResolvedValue({}); const count = await verifySources("qe-1"); // verifyWikipediaUrl is mocked to return true expect(count).toBe(2); expect(mockTopicSourceUpdate).toHaveBeenCalledTimes(2); }); it("returns 0 when no sources exist", async () => { mockTopicSourceFindMany.mockResolvedValue([]); const count = await verifySources("qe-1"); expect(count).toBe(0); expect(mockTopicSourceUpdate).not.toHaveBeenCalled(); }); });