/** * Tests for generateWeeklyReport — the top-level weekly brain health report generator. * * Covers: * - cache hit: returns cached report without calling Claude or DB * - cache miss, < MIN_ACTIVE_DAYS: returns null (gate) * - cache miss, >= MIN_ACTIVE_DAYS: calls Claude, parses response, caches result * - cache miss: returns { report, cached: false } * - cache hit: returns { report, cached: true } * - Claude response is parsed and stored in WeeklyReport shape * - weekOverWeek data from getWeeklyData is included in the returned report * - generatedAt is a valid ISO timestamp * - throws when Claude returns invalid JSON * - throws when Claude returns missing required fields * - throws when highlights is empty array * - throws when areasToFocus is empty array * - throws when Claude network call fails * - caches the result after successful generation * - different userId + same week → different cache key (independent reports) * - same userId + different week → different cache key * - correct haiku model used * - prompt content contains category and XP data * * Strategy: because reportCache is module-level in-memory state, each test * that exercises "cache miss" paths uses a distinct userId (incremented via a * counter) so prior test runs can never produce a spurious cache hit. */ import { describe, it, expect, vi, beforeEach } from "vitest"; // --------------------------------------------------------------------------- // Mock: Prisma (via getWeeklyData which calls prisma internally) // --------------------------------------------------------------------------- const mockUserFindUniqueOrThrow = vi.fn(); const mockActivityFindMany = vi.fn(); vi.mock("@/lib/db", () => ({ prisma: { user: { findUniqueOrThrow: (...args: unknown[]) => mockUserFindUniqueOrThrow(...args), }, activity: { findMany: (...args: unknown[]) => mockActivityFindMany(...args), }, }, })); // --------------------------------------------------------------------------- // Mock: Claude // --------------------------------------------------------------------------- const mockMessagesCreate = vi.fn(); vi.mock("@/lib/claude", () => ({ claude: { messages: { create: (...args: unknown[]) => mockMessagesCreate(...args), }, }, parseClaudeJson: (text: string) => JSON.parse(text.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim()), })); // --------------------------------------------------------------------------- // Import under test (after mocks are wired) // --------------------------------------------------------------------------- import { generateWeeklyReport, type WeeklyReport } from "../weekly-report"; /** Convenience alias for the non-gate branch of the generateWeeklyReport return type */ type ReportResult = { report: WeeklyReport; cached: boolean }; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** Build a Date at UTC noon for a given YYYY-MM-DD */ function utcDay(iso: string): Date { return new Date(`${iso}T12:00:00Z`); } /** Wednesday 2026-03-18 — stable reference date; week starts Monday 2026-03-16 */ const NOW = utcDay("2026-03-18"); /** Counter to generate unique userIds so the in-memory cache never leaks across tests. */ let nextUserId = 100; function freshUserId(): number { return nextUserId++; } /** Base user object returned by DB mock */ const BASE_USER = { streak: 7, longestStreak: 30 }; /** Build a valid Claude response JSON string */ function claudeReport(overrides: Record = {}): string { return JSON.stringify({ report: "Great week overall, strong performance in Chess.", highlights: ["Completed 10 chess puzzles", "Maintained 7-day streak"], areasToFocus: ["Try Feynman challenges", "Aim for 3 logic sessions next week"], ...overrides, }); } /** Wrap Claude response text in the SDK response shape */ function claudeResponse(text: string) { return { content: [{ type: "text", text }], }; } /** 3 activities on distinct days (Mon/Tue/Wed) — always passes the MIN_ACTIVE_DAYS gate */ function threeDistinctDays() { return [ { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-18T10:00:00Z"), score: 0.8, totalXp: 50 }, ]; } /** * Set up mockActivityFindMany to return `currentWeekActivities` for current-week * queries and an empty array for previous-week queries. * * getWeeklyData calls prisma.activity.findMany twice: * 1. { createdAt: { gte: weekStart } } → current week * 2. { createdAt: { gte: prevWeekStart, lt: weekStart } } → previous week (has `lt`) */ function setupActivityMock(currentWeekActivities: object[]) { mockActivityFindMany.mockImplementation( ({ where }: { where: { createdAt?: { lt?: Date; gte: Date } } }) => { if (where?.createdAt?.lt) return Promise.resolve([]); // previous week query return Promise.resolve(currentWeekActivities); }, ); } // --------------------------------------------------------------------------- // Reset common mocks before each test // --------------------------------------------------------------------------- beforeEach(() => { vi.clearAllMocks(); mockUserFindUniqueOrThrow.mockResolvedValue(BASE_USER); setupActivityMock(threeDistinctDays()); mockMessagesCreate.mockResolvedValue(claudeResponse(claudeReport())); }); // --------------------------------------------------------------------------- // Cache hit // --------------------------------------------------------------------------- describe("cache hit", () => { it("returns cached report without calling Claude or DB a second time", async () => { const uid = freshUserId(); // First call — populates cache await generateWeeklyReport(uid, NOW); const priorDbCalls = mockUserFindUniqueOrThrow.mock.calls.length; const priorClaudeCalls = mockMessagesCreate.mock.calls.length; // Second call — should use cache const result = await generateWeeklyReport(uid, NOW) as ReportResult; expect(result).not.toBeNull(); expect(result.cached).toBe(true); expect(mockUserFindUniqueOrThrow).toHaveBeenCalledTimes(priorDbCalls); expect(mockMessagesCreate).toHaveBeenCalledTimes(priorClaudeCalls); }); it("cached result preserves all original report fields", async () => { const uid = freshUserId(); await generateWeeklyReport(uid, NOW); const result = await generateWeeklyReport(uid, NOW) as ReportResult; expect(result.cached).toBe(true); expect(result.report.report).toBe( "Great week overall, strong performance in Chess.", ); expect(result.report.highlights).toEqual([ "Completed 10 chess puzzles", "Maintained 7-day streak", ]); expect(result.report.areasToFocus).toEqual([ "Try Feynman challenges", "Aim for 3 logic sessions next week", ]); }); }); // --------------------------------------------------------------------------- // MIN_ACTIVE_DAYS gate (< 3 active days → null) // --------------------------------------------------------------------------- describe("MIN_ACTIVE_DAYS gate", () => { it("returns gate object (hasReport: false) when activeDaysThisWeek is 2 (< 3)", async () => { setupActivityMock([ { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 50 }, // only 2 distinct days ]); const result = await generateWeeklyReport(freshUserId(), NOW); expect(result).not.toBeNull(); expect("hasReport" in result).toBe(true); const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number }; expect(gate.hasReport).toBe(false); expect(gate.activeDaysThisWeek).toBe(2); expect(gate.requiredDays).toBe(3); expect(mockMessagesCreate).not.toHaveBeenCalled(); }); it("returns gate with activeDaysThisWeek=0 when there are no activities this week", async () => { setupActivityMock([]); const result = await generateWeeklyReport(freshUserId(), NOW); expect("hasReport" in result).toBe(true); const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number }; expect(gate.hasReport).toBe(false); expect(gate.activeDaysThisWeek).toBe(0); expect(mockMessagesCreate).not.toHaveBeenCalled(); }); it("counts only distinct active days (same-day duplicates don't inflate count)", async () => { // 5 activities all on Monday → 1 active day < 3 setupActivityMock([ { category: "chess", createdAt: new Date("2026-03-16T09:00:00Z"), score: 0.9, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.8, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-16T11:00:00Z"), score: 0.7, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-16T12:00:00Z"), score: 0.8, totalXp: 50 }, { category: "chess", createdAt: new Date("2026-03-16T14:00:00Z"), score: 0.9, totalXp: 50 }, ]); const result = await generateWeeklyReport(freshUserId(), NOW); expect("hasReport" in result).toBe(true); const gate = result as { hasReport: false; activeDaysThisWeek: number; requiredDays: number }; expect(gate.activeDaysThisWeek).toBe(1); }); it("passes the gate with exactly 3 distinct active days", async () => { // Default mock already sets up 3 distinct days const result = await generateWeeklyReport(freshUserId(), NOW); expect(result).not.toBeNull(); expect(mockMessagesCreate).toHaveBeenCalledTimes(1); }); }); // --------------------------------------------------------------------------- // Successful generation // --------------------------------------------------------------------------- describe("successful report generation", () => { it("returns { cached: false } on first generation", async () => { const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult; expect(result).not.toBeNull(); expect(result.cached).toBe(false); }); it("report object includes the text from Claude", async () => { const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult; expect(result.report.report).toBe( "Great week overall, strong performance in Chess.", ); expect(result.report.highlights).toEqual([ "Completed 10 chess puzzles", "Maintained 7-day streak", ]); expect(result.report.areasToFocus).toEqual([ "Try Feynman challenges", "Aim for 3 logic sessions next week", ]); }); it("report includes weekOverWeek data from getWeeklyData", async () => { const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult; const wow = result.report.weekOverWeek; expect(wow).toBeDefined(); expect(typeof wow.currentWeekXp).toBe("number"); expect(typeof wow.previousWeekXp).toBe("number"); expect(typeof wow.xpChange).toBe("number"); expect(typeof wow.xpChangePercent).toBe("number"); expect(typeof wow.currentWeekActiveDays).toBe("number"); expect(wow.currentWeekActiveDays).toBe(3); // our 3 distinct test days }); it("currentWeekXp in weekOverWeek matches the sum of activity XP", async () => { // Each of 3 test activities has totalXp = 50 → sum = 150 const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult; expect(result.report.weekOverWeek.currentWeekXp).toBe(150); }); it("report includes a generatedAt ISO timestamp", async () => { const before = Date.now(); const result = await generateWeeklyReport(freshUserId(), NOW) as ReportResult; const after = Date.now(); const ts = new Date(result.report.generatedAt).getTime(); expect(ts).toBeGreaterThanOrEqual(before); expect(ts).toBeLessThanOrEqual(after); }); it("uses the haiku model for cost efficiency", async () => { await generateWeeklyReport(freshUserId(), NOW); const call = mockMessagesCreate.mock.calls[0][0]; expect(call.model).toBe("claude-haiku-4-5-20251001"); }); it("prompt contains total XP data", async () => { setupActivityMock([ { category: "chess", createdAt: new Date("2026-03-16T10:00:00Z"), score: 0.9, totalXp: 200 }, { category: "chess", createdAt: new Date("2026-03-17T10:00:00Z"), score: 0.8, totalXp: 150 }, { category: "chess", createdAt: new Date("2026-03-18T10:00:00Z"), score: 0.7, totalXp: 100 }, ]); await generateWeeklyReport(freshUserId(), NOW); const call = mockMessagesCreate.mock.calls[0][0]; const prompt: string = call.messages[0].content; // Total = 450 XP expect(prompt).toContain("450"); }); it("prompt contains streak data from DB user", async () => { mockUserFindUniqueOrThrow.mockResolvedValue({ streak: 14, longestStreak: 42 }); await generateWeeklyReport(freshUserId(), NOW); const call = mockMessagesCreate.mock.calls[0][0]; const prompt: string = call.messages[0].content; expect(prompt).toContain("14 days"); expect(prompt).toContain("42"); }); it("caches the result so second call doesn't hit Claude", async () => { const uid = freshUserId(); await generateWeeklyReport(uid, NOW); expect(mockMessagesCreate).toHaveBeenCalledTimes(1); await generateWeeklyReport(uid, NOW); expect(mockMessagesCreate).toHaveBeenCalledTimes(1); // no additional call }); }); // --------------------------------------------------------------------------- // Error handling // --------------------------------------------------------------------------- describe("error handling", () => { it("throws when Claude returns invalid JSON", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse("this is not valid JSON {{{"), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(); }); it("throws when Claude returns empty report string", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse(claudeReport({ report: "" })), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow( "invalid weekly report structure", ); }); it("throws when highlights array is missing", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse(JSON.stringify({ report: "A report", areasToFocus: ["something"], // highlights intentionally absent })), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(); }); it("throws when highlights array is empty", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse(claudeReport({ highlights: [] })), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow( "invalid weekly report structure", ); }); it("throws when areasToFocus array is empty", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse(claudeReport({ areasToFocus: [] })), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow( "invalid weekly report structure", ); }); it("throws when areasToFocus is not an array", async () => { mockMessagesCreate.mockResolvedValue( claudeResponse(claudeReport({ areasToFocus: "not an array" })), ); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow(); }); it("throws when Claude network call fails", async () => { mockMessagesCreate.mockRejectedValue(new Error("Network error")); await expect(generateWeeklyReport(freshUserId(), NOW)).rejects.toThrow( "Network error", ); }); it("does NOT cache on error — next call retries Claude", async () => { const uid = freshUserId(); mockMessagesCreate.mockRejectedValueOnce(new Error("Transient failure")); // First call fails await expect(generateWeeklyReport(uid, NOW)).rejects.toThrow(); // Reset to success mockMessagesCreate.mockResolvedValue(claudeResponse(claudeReport())); // Second call should succeed (no stale error cached) const result = await generateWeeklyReport(uid, NOW) as ReportResult; expect(result).not.toBeNull(); expect(result.cached).toBe(false); expect(mockMessagesCreate).toHaveBeenCalledTimes(2); // first failed + second ok }); }); // --------------------------------------------------------------------------- // Cache key isolation // --------------------------------------------------------------------------- describe("cache key isolation", () => { it("different userIds in the same week use separate cache entries", async () => { const uid1 = freshUserId(); const uid2 = freshUserId(); await generateWeeklyReport(uid1, NOW); expect(mockMessagesCreate).toHaveBeenCalledTimes(1); await generateWeeklyReport(uid2, NOW); // different user — different key expect(mockMessagesCreate).toHaveBeenCalledTimes(2); }); it("same userId in a different week generates a fresh report", async () => { const uid = freshUserId(); await generateWeeklyReport(uid, NOW); // week of 2026-03-16 expect(mockMessagesCreate).toHaveBeenCalledTimes(1); const nextWeek = utcDay("2026-03-25"); // week of 2026-03-23 await generateWeeklyReport(uid, nextWeek); expect(mockMessagesCreate).toHaveBeenCalledTimes(2); }); it("same userId, different days within the same week share a cache key", async () => { const uid = freshUserId(); await generateWeeklyReport(uid, utcDay("2026-03-16")); // Monday expect(mockMessagesCreate).toHaveBeenCalledTimes(1); await generateWeeklyReport(uid, utcDay("2026-03-18")); // Wednesday (same ISO week) expect(mockMessagesCreate).toHaveBeenCalledTimes(1); // cache hit — no extra Claude call }); });