File size: 20,501 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/**
 * 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();
  });
});