import { claude, parseClaudeJson } from "@/lib/claude"; import type { PerformanceSummary } from "@/lib/performance"; import type { DifficultyRecommendations } from "@/lib/difficulty"; import { getRecommendedSettings } from "@/lib/difficulty"; import { CATEGORY_LABELS, type Category } from "@/config/xp"; import { createHash } from "crypto"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface CoachFeedback { feedback: string; recommendedExercise: { category: Category; difficulty: string; }; encouragement: string; } interface CacheEntry { feedback: CoachFeedback; cachedAt: number; } // --------------------------------------------------------------------------- // Configuration // --------------------------------------------------------------------------- /** Cache TTL: 3 hours in milliseconds */ const CACHE_TTL_MS = 3 * 60 * 60 * 1000; /** Max requests per user per hour */ const RATE_LIMIT_MAX = 10; /** Rate limit window: 1 hour in milliseconds */ const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000; // --------------------------------------------------------------------------- // In-memory caches (reset on server restart, which is fine for dev/MVP) // --------------------------------------------------------------------------- const feedbackCache = new Map(); /** Map of userId → array of request timestamps */ const rateLimitMap = new Map(); // --------------------------------------------------------------------------- // Cache key generation // --------------------------------------------------------------------------- /** * Build a cache key by hashing the user ID + rounded performance metrics. * Small changes (±2% success rate, same streak bucket) won't bust the cache. */ export function buildCacheKey( userId: number, summary: PerformanceSummary, ): string { const roundedCategories = summary.categories.map((c) => ({ cat: c.category, sr: Math.round(c.successRate / 5) * 5, // Round to nearest 5% trend: c.trend, attempts: Math.round(c.attempts / 5) * 5, // Round to nearest 5 })); const payload = JSON.stringify({ userId, streak: Math.min(summary.streakDays, 30), // Cap streak granularity overallScore: Math.round(summary.overallScore / 5) * 5, cats: roundedCategories, }); return createHash("sha256").update(payload).digest("hex").slice(0, 16); } // --------------------------------------------------------------------------- // Rate limiting // --------------------------------------------------------------------------- /** * Check if a user has exceeded the rate limit. * Returns true if the request should be blocked. */ export function isRateLimited(userId: number): boolean { const now = Date.now(); const timestamps = rateLimitMap.get(userId) ?? []; // Prune expired entries const active = timestamps.filter( (t) => now - t < RATE_LIMIT_WINDOW_MS, ); rateLimitMap.set(userId, active); return active.length >= RATE_LIMIT_MAX; } /** * Record a request for rate-limiting purposes. */ export function recordRequest(userId: number): void { const now = Date.now(); const timestamps = rateLimitMap.get(userId) ?? []; timestamps.push(now); rateLimitMap.set(userId, timestamps); } // --------------------------------------------------------------------------- // Cache operations // --------------------------------------------------------------------------- /** * Get a cached feedback response if it exists and hasn't expired. */ export function getCachedFeedback(key: string): CoachFeedback | null { const entry = feedbackCache.get(key); if (!entry) return null; if (Date.now() - entry.cachedAt > CACHE_TTL_MS) { feedbackCache.delete(key); return null; } return entry.feedback; } /** * Store feedback in cache. */ export function cacheFeedback(key: string, feedback: CoachFeedback): void { feedbackCache.set(key, { feedback, cachedAt: Date.now() }); } // --------------------------------------------------------------------------- // Prompt construction // --------------------------------------------------------------------------- /** * Build the Claude prompt from performance data and difficulty recommendations. */ export function buildPrompt( summary: PerformanceSummary, recommendations: DifficultyRecommendations, ): string { const catSummaries = summary.categories .filter((c) => c.attempts > 0) .map((c) => { const rec = recommendations.recommendations[c.category]; return `- ${CATEGORY_LABELS[c.category]}: ${c.successRate}% success rate, ${c.attempts} attempts, level ${c.level}, trend: ${c.trend}, recommended difficulty: ${rec?.difficulty ?? "medium"}`; }) .join("\n"); const inactiveCategories = summary.categories .filter((c) => c.attempts === 0) .map((c) => CATEGORY_LABELS[c.category]); const inactiveNote = inactiveCategories.length > 0 ? `\nUnexplored categories: ${inactiveCategories.join(", ")}` : ""; return `You are the Active Coach for RotNot, a brain training app that combats cognitive atrophy from AI over-reliance. Analyze the user's performance and provide personalized coaching feedback. User Performance: - Overall score: ${summary.overallScore}% - Streak: ${summary.streakDays} days (longest: ${summary.longestStreak}) - Total exercises completed: ${summary.totalExercises} - Active days: ${summary.activeDays} - Last activity: ${summary.lastActivityAt ?? "never"} Category Breakdown: ${catSummaries || "No exercises completed yet."}${inactiveNote} Instructions: 1. "feedback": 2-3 actionable sentences about their performance. Reference specific categories and trends. Do NOT be generic. 2. "recommendedExercise": Pick the single best category and difficulty for them right now. Use one of: chess, reading, feynman, logic, critical-thinking, quests. Difficulty: easy, medium, or hard. 3. "encouragement": 1 sentence of genuine, specific encouragement (not generic "keep it up!" — reference something real from their data). Respond ONLY in valid JSON (no markdown, no code fences): { "feedback": "...", "recommendedExercise": { "category": "...", "difficulty": "..." }, "encouragement": "..." }`; } // --------------------------------------------------------------------------- // Main feedback generator // --------------------------------------------------------------------------- /** * Generate coach feedback for a user. Uses cache if available, * otherwise calls Claude Haiku. * * Throws if Claude call fails or returns invalid JSON. */ export async function generateCoachFeedback( userId: number, summary: PerformanceSummary, ): Promise<{ feedback: CoachFeedback; cached: boolean }> { const recommendations = getRecommendedSettings(summary); const cacheKey = buildCacheKey(userId, summary); // Check cache first const cached = getCachedFeedback(cacheKey); if (cached) { return { feedback: cached, cached: true }; } // Build prompt and call Claude const prompt = buildPrompt(summary, recommendations); const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 512, messages: [{ role: "user", content: prompt }], }); const text = message.content[0].type === "text" ? message.content[0].text : ""; const parsed = parseClaudeJson(text) as CoachFeedback; // Validate response shape if ( !parsed.feedback || typeof parsed.feedback !== "string" || !parsed.recommendedExercise || !parsed.recommendedExercise.category || !parsed.recommendedExercise.difficulty || !parsed.encouragement || typeof parsed.encouragement !== "string" ) { throw new Error("Claude returned invalid feedback structure"); } // Cache the result cacheFeedback(cacheKey, parsed); return { feedback: parsed, cached: false }; }