import { describe, it, expect, beforeEach, vi } from "vitest"; import { buildCacheKey, isRateLimited, recordRequest, getCachedFeedback, cacheFeedback, buildPrompt, } from "../coach-feedback"; import { getRecommendedSettings } from "../difficulty"; import type { PerformanceSummary } from "../performance"; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function makeSummary( overrides: Partial = {}, ): PerformanceSummary { return { categories: [ { category: "chess", label: "Chess", successRate: 65, attempts: 12, avgScore: 0.65, avgDurationSecs: null, totalXp: 300, level: 3, trend: "improving", }, { category: "reading", label: "Deep Reading", successRate: 40, attempts: 5, avgScore: 0.4, avgDurationSecs: 120, totalXp: 100, level: 2, trend: "stable", }, { category: "feynman", label: "Feynman", successRate: 0, attempts: 0, avgScore: 0, avgDurationSecs: null, totalXp: 0, level: 1, trend: "new", }, { category: "logic", label: "Logic Puzzles", successRate: 80, attempts: 20, avgScore: 0.8, avgDurationSecs: 60, totalXp: 500, level: 5, trend: "stable", }, { category: "critical-thinking", label: "Critical Thinking", successRate: 50, attempts: 8, avgScore: 0.5, avgDurationSecs: 90, totalXp: 200, level: 2, trend: "declining", }, { category: "quests", label: "Skill Quests", successRate: 70, attempts: 10, avgScore: 0.7, avgDurationSecs: null, totalXp: 250, level: 3, trend: "improving", }, ], overallScore: 55, streakDays: 3, longestStreak: 7, totalExercises: 55, activeDays: 10, lastActivityAt: "2026-03-20T01:00:00.000Z", ...overrides, }; } // --------------------------------------------------------------------------- // buildCacheKey // --------------------------------------------------------------------------- describe("buildCacheKey", () => { it("returns a hex string of 16 characters", () => { const key = buildCacheKey(1, makeSummary()); expect(key).toMatch(/^[0-9a-f]{16}$/); }); it("returns the same key for identical inputs", () => { const summary = makeSummary(); const a = buildCacheKey(1, summary); const b = buildCacheKey(1, summary); expect(a).toBe(b); }); it("returns different keys for different users", () => { const summary = makeSummary(); const a = buildCacheKey(1, summary); const b = buildCacheKey(2, summary); expect(a).not.toBe(b); }); it("returns the same key for small success rate changes within rounding", () => { const s1 = makeSummary(); const s2 = makeSummary(); // Modify chess success rate within the ±2.5% rounding window s1.categories[0] = { ...s1.categories[0], successRate: 63 }; s2.categories[0] = { ...s2.categories[0], successRate: 64 }; expect(buildCacheKey(1, s1)).toBe(buildCacheKey(1, s2)); }); it("returns a different key when success rate crosses rounding boundary", () => { const s1 = makeSummary(); const s2 = makeSummary(); s1.categories[0] = { ...s1.categories[0], successRate: 62 }; s2.categories[0] = { ...s2.categories[0], successRate: 68 }; expect(buildCacheKey(1, s1)).not.toBe(buildCacheKey(1, s2)); }); }); // --------------------------------------------------------------------------- // Rate limiting // --------------------------------------------------------------------------- describe("isRateLimited / recordRequest", () => { // Reset rate limit state between tests by recording to a unique user ID let testUserId: number; beforeEach(() => { // Use a unique user ID per test to avoid cross-test interference testUserId = Math.floor(Math.random() * 1_000_000) + 1000; }); it("allows requests below the limit", () => { expect(isRateLimited(testUserId)).toBe(false); }); it("blocks after 10 requests in an hour", () => { for (let i = 0; i < 10; i++) { recordRequest(testUserId); } expect(isRateLimited(testUserId)).toBe(true); }); it("allows 9 requests without blocking", () => { for (let i = 0; i < 9; i++) { recordRequest(testUserId); } expect(isRateLimited(testUserId)).toBe(false); }); }); // --------------------------------------------------------------------------- // Cache operations // --------------------------------------------------------------------------- describe("getCachedFeedback / cacheFeedback", () => { const testFeedback = { feedback: "You're doing great at chess but need more reading practice.", recommendedExercise: { category: "reading" as const, difficulty: "medium", }, encouragement: "Your 3-day streak shows real commitment!", }; it("returns null for non-existent key", () => { expect(getCachedFeedback("nonexistent-key-xyz")).toBeNull(); }); it("returns cached feedback when it exists", () => { const key = "test-cache-key-" + Date.now(); cacheFeedback(key, testFeedback); const result = getCachedFeedback(key); expect(result).toEqual(testFeedback); }); it("returns null for expired cache entries", () => { const key = "test-expired-key-" + Date.now(); cacheFeedback(key, testFeedback); // Manually expire by advancing time vi.useFakeTimers(); vi.advanceTimersByTime(3 * 60 * 60 * 1000 + 1); // 3h + 1ms const result = getCachedFeedback(key); expect(result).toBeNull(); vi.useRealTimers(); }); }); // --------------------------------------------------------------------------- // buildPrompt // --------------------------------------------------------------------------- describe("buildPrompt", () => { it("includes category data in the prompt", () => { const summary = makeSummary(); const recommendations = getRecommendedSettings(summary); const prompt = buildPrompt(summary, recommendations); expect(prompt).toContain("Chess"); expect(prompt).toContain("65%"); expect(prompt).toContain("improving"); expect(prompt).toContain("Active Coach"); }); it("includes streak and overall data", () => { const summary = makeSummary(); const recommendations = getRecommendedSettings(summary); const prompt = buildPrompt(summary, recommendations); expect(prompt).toContain("Streak: 3 days"); expect(prompt).toContain("longest: 7"); expect(prompt).toContain("Total exercises completed: 55"); }); it("mentions unexplored categories", () => { const summary = makeSummary(); const recommendations = getRecommendedSettings(summary); const prompt = buildPrompt(summary, recommendations); expect(prompt).toContain("Unexplored categories"); expect(prompt).toContain("Feynman"); }); it("handles a user with no exercises", () => { const summary = makeSummary({ categories: makeSummary().categories.map((c) => ({ ...c, attempts: 0, successRate: 0, })), totalExercises: 0, overallScore: 0, }); const recommendations = getRecommendedSettings(summary); const prompt = buildPrompt(summary, recommendations); expect(prompt).toContain("No exercises completed yet."); }); it("requests JSON-only output", () => { const summary = makeSummary(); const recommendations = getRecommendedSettings(summary); const prompt = buildPrompt(summary, recommendations); expect(prompt).toContain("ONLY in valid JSON"); expect(prompt).toContain("no markdown"); }); });